{"id":3355,"date":"2020-04-19T19:00:39","date_gmt":"2020-04-19T19:00:39","guid":{"rendered":"https:\/\/www.aiproblog.com\/index.php\/2020\/04\/19\/how-to-develop-a-random-forest-ensemble-in-python\/"},"modified":"2020-04-19T19:00:39","modified_gmt":"2020-04-19T19:00:39","slug":"how-to-develop-a-random-forest-ensemble-in-python","status":"publish","type":"post","link":"https:\/\/www.aiproblog.com\/index.php\/2020\/04\/19\/how-to-develop-a-random-forest-ensemble-in-python\/","title":{"rendered":"How to Develop a Random Forest Ensemble in Python"},"content":{"rendered":"<p>Author: Jason Brownlee<\/p>\n<div>\n<p>Random forest is an ensemble machine learning algorithm.<\/p>\n<p>It is perhaps the most popular and widely used machine learning algorithm given its good or excellent performance across a wide range of classification and regression predictive modeling problems.<\/p>\n<p>It is also easy to use given that it has few key hyperparameters and sensible heuristics for configuring these hyperparameters.<\/p>\n<p>In this tutorial, you will discover how to develop a random forest ensemble for classification and regression.<\/p>\n<p>After completing this tutorial, you will know:<\/p>\n<ul>\n<li>Random forest ensemble is an ensemble of decision trees and a natural extension of bagging.<\/li>\n<li>How to use the random forest ensemble for classification and regression with scikit-learn.<\/li>\n<li>How to explore the effect of random forest model hyperparameters on model performance.<\/li>\n<\/ul>\n<p>Let&rsquo;s get started.<\/p>\n<div id=\"attachment_10209\" style=\"width: 809px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-10209\" class=\"size-full wp-image-10209\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2020\/04\/How-to-Develop-a-Random-Forest-Ensemble-in-Python.jpg\" alt=\"How to Develop a Random Forest Ensemble in Python\" width=\"799\" height=\"555\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/How-to-Develop-a-Random-Forest-Ensemble-in-Python.jpg 799w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/How-to-Develop-a-Random-Forest-Ensemble-in-Python-300x208.jpg 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/How-to-Develop-a-Random-Forest-Ensemble-in-Python-768x533.jpg 768w\" sizes=\"(max-width: 799px) 100vw, 799px\"><\/p>\n<p id=\"caption-attachment-10209\" class=\"wp-caption-text\">How to Develop a Random Forest Ensemble in Python<br \/>Photo by <a href=\"https:\/\/flickr.com\/photos\/sheila_sund\/30461181307\/\">Sheila Sund<\/a>, some rights reserved.<\/p>\n<\/div>\n<h2>Tutorial Overview<\/h2>\n<p>This tutorial is divided into three parts; they are:<\/p>\n<ol>\n<li>Random Forest Algorithm<\/li>\n<li>Random Forest Scikit-Learn API\n<ol>\n<li>Random Forest for Classification<\/li>\n<li>Random Forest for Regression<\/li>\n<\/ol>\n<\/li>\n<li>Random Forest Hyperparameters\n<ol>\n<li>Explore Number of Samples<\/li>\n<li>Explore Number of Features<\/li>\n<li>Explore Number of Trees<\/li>\n<li>Explore Tree Depth<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<h2>Random Forest Algorithm<\/h2>\n<p>Random forest is an ensemble of decision tree algorithms.<\/p>\n<p>It is an extension of bootstrap aggregation (bagging) of decision trees and can be used for classification and regression problems.<\/p>\n<p>In bagging, a number of decision trees are created where each tree is created from a different bootstrap sample of the training dataset. A <a href=\"https:\/\/machinelearningmastery.com\/a-gentle-introduction-to-the-bootstrap-method\/\">bootstrap sample<\/a> is a sample of the training dataset where a sample may appear more than once in the sample, referred to as <strong>sampling with replacement<\/strong>.<\/p>\n<p>Bagging is an effective ensemble algorithm as each decision tree is fit on a slightly different training dataset, and in turn, has a slightly different performance. Unlike normal decision tree models, such as <a href=\"https:\/\/machinelearningmastery.com\/classification-and-regression-trees-for-machine-learning\/\">classification and regression trees<\/a> (CART), trees used in the ensemble are unpruned, making them slightly overfit to the training dataset. This is desirable as it helps to make each tree more different and have less correlated predictions or prediction errors.<\/p>\n<p>Predictions from the trees are averaged across all decision trees resulting in better performance than any single tree in the model.<\/p>\n<blockquote>\n<p>Each model in the ensemble is then used to generate a prediction for a new sample and these m predictions are averaged to give the forest&rsquo;s prediction<\/p>\n<\/blockquote>\n<p>&mdash; Page 199, <a href=\"https:\/\/amzn.to\/2O3BuOa\">Applied Predictive Modeling<\/a>, 2013.<\/p>\n<p>A prediction on a regression problem is the average of the prediction across the trees in the ensemble. A prediction on a classification problem is the majority vote for the class label across the trees in the ensemble.<\/p>\n<ul>\n<li><strong>Regression<\/strong>: Prediction is the average prediction across the decision trees.<\/li>\n<li><strong>Classification<\/strong>: Prediction is the majority vote class label predicted across the decision trees.<\/li>\n<\/ul>\n<blockquote>\n<p>As with bagging, each tree in the forest casts a vote for the classification of a new sample, and the proportion of votes in each class across the ensemble is the predicted probability vector.<\/p>\n<\/blockquote>\n<p>&mdash; Page 387, <a href=\"https:\/\/amzn.to\/2O3BuOa\">Applied Predictive Modeling<\/a>, 2013.<\/p>\n<p>Random forest involves constructing a large number of decision trees from bootstrap samples from the training dataset, like bagging.<\/p>\n<p>Unlike bagging, random forest also involves selecting a subset of input features (columns or variables) at each split point in the construction of trees. Typically, constructing a decision tree involves evaluating the value for each input variable in the data in order to select a split point. By reducing the features to a random subset that may be considered at each split point, it forces each decision tree in the ensemble to be more different.<\/p>\n<blockquote>\n<p>Random forests provide an improvement over bagged trees by way of a small tweak that decorrelates the trees. [&hellip;] But when building these decision trees, each time a split in a tree is considered, a random sample of m predictors is chosen as split candidates from the full set of p predictors.<\/p>\n<\/blockquote>\n<p>&mdash; Page 320, <a href=\"https:\/\/amzn.to\/37xa7DT\">An Introduction to Statistical Learning with Applications in R<\/a>, 2014.<\/p>\n<p>The effect is that the predictions, and in turn, prediction errors, made by each tree in the ensemble are more different or less correlated. When the predictions from these less correlated trees are averaged to make a prediction, it often results in better performance than bagged decision trees.<\/p>\n<p>Perhaps the most important hyperparameter to tune for the random forest is the number of random features to consider at each split point.<\/p>\n<blockquote>\n<p>Random forests&rsquo; tuning parameter is the number of randomly selected predictors, k, to choose from at each split, and is commonly referred to as mtry. In the regression context, Breiman (2001) recommends setting mtry to be one-third of the number of predictors.<\/p>\n<\/blockquote>\n<p>&mdash; Page 199, <a href=\"https:\/\/amzn.to\/2O3BuOa\">Applied Predictive Modeling<\/a>, 2013.<\/p>\n<p>A good heuristic for regression is to set this hyperparameter to 1\/3 the number of input features.<\/p>\n<ul>\n<li>num_features_for_split = total_input_features \/ 3<\/li>\n<\/ul>\n<blockquote>\n<p>For classification problems, Breiman (2001) recommends setting mtry to the square root of the number of predictors.<\/p>\n<\/blockquote>\n<p>&mdash; Page 387, <a href=\"https:\/\/amzn.to\/2O3BuOa\">Applied Predictive Modeling<\/a>, 2013.<\/p>\n<p>A good heuristic for classification is to set this hyperparameter to the square root of the number of input features.<\/p>\n<ul>\n<li>num_features_for_split = sqrt(total_input_features)<\/li>\n<\/ul>\n<p>Another important hyperparameter to tune is the depth of the decision trees. Deeper trees are often more overfit to the training data, but also less correlated, which in turn may improve the performance of the ensemble. Depths from 1 to 10 levels may be effective.<\/p>\n<p>Finally, the number of decision trees in the ensemble can be set. Often, this is increased until no further improvement is seen.<\/p>\n<h2>Random Forest Scikit-Learn API<\/h2>\n<p>Random Forest ensembles can be implemented from scratch, although this can be challenging for beginners.<\/p>\n<p>The scikit-learn Python machine learning library provides an implementation of Random Forest for machine learning.<\/p>\n<p>It is available in modern versions of the library.<\/p>\n<p>First, confirm that you are using a modern version of the library by running the following script:<\/p>\n<pre class=\"crayon-plain-tag\"># check scikit-learn version\r\nimport sklearn\r\nprint(sklearn.__version__)<\/pre>\n<p>Running the script will print your version of scikit-learn.<\/p>\n<p>Your version should be the same or higher. If not, you must upgrade your version of the scikit-learn library.<\/p>\n<pre class=\"crayon-plain-tag\">0.22.1<\/pre>\n<p>Random Forest is provided via the <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.ensemble.RandomForestRegressor.html\">RandomForestRegressor<\/a> and <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.ensemble.RandomForestClassifier.html\">RandomForestClassifier<\/a> classes.<\/p>\n<p>Both models operate the same way and take the same arguments that influence how the decision trees are created.<\/p>\n<p>Randomness is used in the construction of the model. This means that each time the algorithm is run on the same data, it will produce a slightly different model.<\/p>\n<p>When using machine learning algorithms that have a stochastic learning algorithm, it is good practice to evaluate them by averaging their performance across multiple runs or repeats of <a href=\"https:\/\/machinelearningmastery.com\/k-fold-cross-validation\/\">cross-validation<\/a>. When fitting a final model, it may be desirable to either increase the number of trees until the variance of the model is reduced across repeated evaluations, or to fit multiple final models and average their predictions.<\/p>\n<p>Let&rsquo;s take a look at how to develop a Random Forest ensemble for both classification and regression tasks.<\/p>\n<h3>Random Forest for Classification<\/h3>\n<p>In this section, we will look at using Random Forest for a classification problem.<\/p>\n<p>First, we can use the <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.datasets.make_classification.html\">make_classification() function<\/a> to create a synthetic binary classification problem with 1,000 examples and 20 input features.<\/p>\n<p>The complete example is listed below.<\/p>\n<pre class=\"crayon-plain-tag\"># test classification dataset\r\nfrom sklearn.datasets import make_classification\r\n# define dataset\r\nX, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=3)\r\n# summarize the dataset\r\nprint(X.shape, y.shape)<\/pre>\n<p>Running the example creates the dataset and summarizes the shape of the input and output components.<\/p>\n<pre class=\"crayon-plain-tag\">(1000, 20) (1000,)<\/pre>\n<p>Next, we can evaluate a random forest algorithm on this dataset.<\/p>\n<p>We will evaluate the model using <a href=\"https:\/\/machinelearningmastery.com\/cross-validation-for-imbalanced-classification\/\">repeated stratified k-fold cross-validation<\/a>, with three repeats and 10 folds. We will report the mean and standard deviation of the accuracy of the model across all repeats and folds.<\/p>\n<pre class=\"crayon-plain-tag\"># evaluate random forest algorithm for classification\r\nfrom numpy import mean\r\nfrom numpy import std\r\nfrom sklearn.datasets import make_classification\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import RepeatedStratifiedKFold\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n# define dataset\r\nX, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=3)\r\n# define the model\r\nmodel = RandomForestClassifier()\r\n# evaluate the model\r\ncv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\r\nn_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\r\n# report performance\r\nprint('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))<\/pre>\n<p>Running the example reports the mean and standard deviation accuracy of the model.<\/p>\n<p>Your specific results may vary given the stochastic nature of the learning algorithm. Try running the example a few times.<\/p>\n<p>In this case, we can see the random forest ensemble with default hyperparameters achieves a classification accuracy of about 90.5 percent.<\/p>\n<pre class=\"crayon-plain-tag\">Accuracy: 0.905 (0.025)<\/pre>\n<p>We can also use the random forest model as a final model and make predictions for classification.<\/p>\n<p>First, the random forest ensemble is fit on all available data, then the <em>predict()<\/em> function can be called to make predictions on new data.<\/p>\n<p>The example below demonstrates this on our binary classification dataset.<\/p>\n<pre class=\"crayon-plain-tag\"># make predictions using random forest for classification\r\nfrom sklearn.datasets import make_classification\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n# define dataset\r\nX, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=3)\r\n# define the model\r\nmodel = RandomForestClassifier()\r\n# fit the model on the whole dataset\r\nmodel.fit(X, y)\r\n# make a single prediction\r\nrow = [[-8.52381793,5.24451077,-12.14967704,-2.92949242,0.99314133,0.67326595,-0.38657932,1.27955683,-0.60712621,3.20807316,0.60504151,-1.38706415,8.92444588,-7.43027595,-2.33653219,1.10358169,0.21547782,1.05057966,0.6975331,0.26076035]]\r\nyhat = model.predict(row)\r\nprint('Predicted Class: %d' % yhat[0])<\/pre>\n<p>Running the example fits the random forest ensemble model on the entire dataset and is then used to make a prediction on a new row of data, as we might when using the model in an application.<\/p>\n<pre class=\"crayon-plain-tag\">Predicted Class: 0<\/pre>\n<p>Now that we are familiar with using random forest for classification, let&rsquo;s look at the API for regression.<\/p>\n<h3>Random Forest for Regression<\/h3>\n<p>In this section, we will look at using random forests for a regression problem.<\/p>\n<p>First, we can use the <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.datasets.make_regression.html\">make_regression() function<\/a> to create a synthetic regression problem with 1,000 examples and 20 input features.<\/p>\n<p>The complete example is listed below.<\/p>\n<pre class=\"crayon-plain-tag\"># test regression dataset\r\nfrom sklearn.datasets import make_regression\r\n# define dataset\r\nX, y = make_regression(n_samples=1000, n_features=20, n_informative=15, noise=0.1, random_state=2)\r\n# summarize the dataset\r\nprint(X.shape, y.shape)<\/pre>\n<p>Running the example creates the dataset and summarizes the shape of the input and output components.<\/p>\n<pre class=\"crayon-plain-tag\">(1000, 20) (1000,)<\/pre>\n<p>Next, we can evaluate a random forest algorithm on this dataset.<\/p>\n<p>As we did with the last section, we will evaluate the model using repeated k-fold cross-validation, with three repeats and 10 folds. We will report the mean absolute error (MAE) of the model across all repeats and folds. The scikit-learn library makes the MAE negative so that it is maximized instead of minimized. This means that larger negative MAE are better and a perfect model has a MAE of 0.<\/p>\n<p>The complete example is listed below.<\/p>\n<pre class=\"crayon-plain-tag\"># evaluate random forest ensemble for regression\r\nfrom numpy import mean\r\nfrom numpy import std\r\nfrom sklearn.datasets import make_regression\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import RepeatedKFold\r\nfrom sklearn.ensemble import RandomForestRegressor\r\n# define dataset\r\nX, y = make_regression(n_samples=1000, n_features=20, n_informative=15, noise=0.1, random_state=2)\r\n# define the model\r\nmodel = RandomForestRegressor()\r\n# evaluate the model\r\ncv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)\r\nn_scores = cross_val_score(model, X, y, scoring='neg_mean_absolute_error', cv=cv, n_jobs=-1, error_score='raise')\r\n# report performance\r\nprint('MAE: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))<\/pre>\n<p>Running the example reports the mean and standard deviation accuracy of the model.<\/p>\n<p>Your specific results may vary given the stochastic nature of the learning algorithm. Try running the example a few times.<\/p>\n<p>In this case, we can see the random forest ensemble with default hyperparameters achieves a MAE of about 90.<\/p>\n<pre class=\"crayon-plain-tag\">MAE: -90.149 (7.924)<\/pre>\n<p>We can also use the random forest model as a final model and make predictions for regression.<\/p>\n<p>First, the random forest ensemble is fit on all available data, then the <em>predict()<\/em> function can be called to make predictions on new data.<\/p>\n<p>The example below demonstrates this on our regression dataset.<\/p>\n<pre class=\"crayon-plain-tag\"># random forest for making predictions for regression\r\nfrom sklearn.datasets import make_regression\r\nfrom sklearn.ensemble import RandomForestRegressor\r\n# define dataset\r\nX, y = make_regression(n_samples=1000, n_features=20, n_informative=15, noise=0.1, random_state=2)\r\n# define the model\r\nmodel = RandomForestRegressor()\r\n# fit the model on the whole dataset\r\nmodel.fit(X, y)\r\n# make a single prediction\r\nrow = [[-0.89483109,-1.0670149,-0.25448694,-0.53850126,0.21082105,1.37435592,0.71203659,0.73093031,-1.25878104,-2.01656886,0.51906798,0.62767387,0.96250155,1.31410617,-1.25527295,-0.85079036,0.24129757,-0.17571721,-1.11454339,0.36268268]]\r\nyhat = model.predict(row)\r\nprint('Prediction: %d' % yhat[0])<\/pre>\n<p>Running the example fits the random forest ensemble model on the entire dataset and is then used to make a prediction on a new row of data, as we might when using the model in an application.<\/p>\n<pre class=\"crayon-plain-tag\">Prediction: -173<\/pre>\n<p>Now that we are familiar with using the scikit-learn API to evaluate and use random forest ensembles, let&rsquo;s look at configuring the model.<\/p>\n<h2>Random Forest Hyperparameters<\/h2>\n<p>In this section, we will take a closer look at some of the hyperparameters you should consider tuning for the random forest ensemble and their effect on model performance.<\/p>\n<h3>Explore Number of Samples<\/h3>\n<p>Each decision tree in the ensemble is fit on a <a href=\"https:\/\/machinelearningmastery.com\/a-gentle-introduction-to-the-bootstrap-method\/\">bootstrap sample<\/a> drawn from the training dataset.<\/p>\n<p>This can be turned off by setting the &ldquo;<em>bootstrap<\/em>&rdquo; argument to <em>False<\/em>, if you desire. In that case, the whole training dataset will be used to train each decision tree. <strong>This is not recommended<\/strong>.<\/p>\n<p>The &ldquo;<em>max_samples<\/em>&rdquo; argument can be set to a float between 0 and 1 to control the percentage of the size of the training dataset to make the bootstrap sample used to train each decision tree.<\/p>\n<p>For example, if the training dataset has 100 rows, the <em>max_samples<\/em> argument could be set to 0.5 and each decision tree will be fit on a bootstrap sample with (100 * 0.5) or 50 rows of data.<\/p>\n<p>A smaller sample size will make trees more different, and a larger sample size will make the trees more similar. Setting <em>max_samples<\/em> to &ldquo;<em>None<\/em>&rdquo; will make the sample size the same size as the training dataset and this is the default.<\/p>\n<p>The example below demonstrates the effect of different bootstrap sample sizes from 10 percent to 100 percent on the random forest algorithm.<\/p>\n<pre class=\"crayon-plain-tag\"># explore random forest bootstrap sample size on performance\r\nfrom numpy import mean\r\nfrom numpy import std\r\nfrom sklearn.datasets import make_classification\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import RepeatedStratifiedKFold\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom matplotlib import pyplot\r\n\r\n# get the dataset\r\ndef get_dataset():\r\n\tX, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=3)\r\n\treturn X, y\r\n\r\n# get a list of models to evaluate\r\ndef get_models():\r\n\tmodels = dict()\r\n\tmodels['10'] = RandomForestClassifier(max_samples=0.1)\r\n\tmodels['20'] = RandomForestClassifier(max_samples=0.2)\r\n\tmodels['30'] = RandomForestClassifier(max_samples=0.3)\r\n\tmodels['40'] = RandomForestClassifier(max_samples=0.4)\r\n\tmodels['50'] = RandomForestClassifier(max_samples=0.5)\r\n\tmodels['60'] = RandomForestClassifier(max_samples=0.6)\r\n\tmodels['70'] = RandomForestClassifier(max_samples=0.7)\r\n\tmodels['80'] = RandomForestClassifier(max_samples=0.8)\r\n\tmodels['90'] = RandomForestClassifier(max_samples=0.9)\r\n\tmodels['100'] = RandomForestClassifier(max_samples=None)\r\n\treturn models\r\n\r\n# evaluate a give model using cross-validation\r\ndef evaluate_model(model):\r\n\tcv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\r\n\tscores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\r\n\treturn scores\r\n\r\n# define dataset\r\nX, y = get_dataset()\r\n# get the models to evaluate\r\nmodels = get_models()\r\n# evaluate the models and store results\r\nresults, names = list(), list()\r\nfor name, model in models.items():\r\n\tscores = evaluate_model(model)\r\n\tresults.append(scores)\r\n\tnames.append(name)\r\n\tprint('&gt;%s %.3f (%.3f)' % (name, mean(scores), std(scores)))\r\n# plot model performance for comparison\r\npyplot.boxplot(results, labels=names, showmeans=True)\r\npyplot.xticks(rotation=45)\r\npyplot.show()<\/pre>\n<p>Running the example first reports the mean accuracy for each dataset size.<\/p>\n<p>In this case, the results suggest that using a bootstrap sample size that is equal to the size of the training dataset achieves the best results on this dataset.<\/p>\n<p>This is the default and it should probably be used in most cases.<\/p>\n<pre class=\"crayon-plain-tag\">&gt;10 0.856 (0.031)\r\n&gt;20 0.873 (0.029)\r\n&gt;30 0.881 (0.021)\r\n&gt;40 0.891 (0.033)\r\n&gt;50 0.893 (0.025)\r\n&gt;60 0.897 (0.030)\r\n&gt;70 0.902 (0.024)\r\n&gt;80 0.903 (0.024)\r\n&gt;90 0.900 (0.026)\r\n&gt;100 0.903 (0.027)<\/pre>\n<p>A box and whisker plot is created for the distribution of accuracy scores for each bootstrap sample size.<\/p>\n<p>In this case, we can see a general trend that the larger the sample, the better the performance of the model.<\/p>\n<p>You might like to extend this example and see what happens if the bootstrap sample size is larger or even much larger than the training dataset (e.g. you can set an integer value as the number of samples instead of a float percentage of the training dataset size).<\/p>\n<div id=\"attachment_10205\" style=\"width: 1290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-10205\" class=\"size-full wp-image-10205\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Bootstrap-Sample-Size-vs-Classification-Accuracy.png\" alt=\"Box Plot of Random Forest Bootstrap Sample Size vs. Classification Accuracy\" width=\"1280\" height=\"960\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Bootstrap-Sample-Size-vs-Classification-Accuracy.png 1280w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Bootstrap-Sample-Size-vs-Classification-Accuracy-300x225.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Bootstrap-Sample-Size-vs-Classification-Accuracy-1024x768.png 1024w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Bootstrap-Sample-Size-vs-Classification-Accuracy-768x576.png 768w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"><\/p>\n<p id=\"caption-attachment-10205\" class=\"wp-caption-text\">Box Plot of Random Forest Bootstrap Sample Size vs. Classification Accuracy<\/p>\n<\/div>\n<h3>Explore Number of Features<\/h3>\n<p>The number of features that is randomly sampled for each split point is perhaps the most important feature to configure for random forest.<\/p>\n<p>It is set via the <em>max_features<\/em> argument and defaults to the square root of the number of input features. In this case, for our test dataset, this would be <em>sqrt(20)<\/em> or about four features.<\/p>\n<p>The example below explores the effect of the number of features randomly selected at each split point on model accuracy. We will try values from 1 to 7 and would expect a small value, around four, to perform well based on the heuristic.<\/p>\n<pre class=\"crayon-plain-tag\"># explore random forest number of features effect on performance\r\nfrom numpy import mean\r\nfrom numpy import std\r\nfrom sklearn.datasets import make_classification\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import RepeatedStratifiedKFold\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom matplotlib import pyplot\r\n\r\n# get the dataset\r\ndef get_dataset():\r\n\tX, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=3)\r\n\treturn X, y\r\n\r\n# get a list of models to evaluate\r\ndef get_models():\r\n\tmodels = dict()\r\n\tmodels['1'] = RandomForestClassifier(max_features=1)\r\n\tmodels['2'] = RandomForestClassifier(max_features=2)\r\n\tmodels['3'] = RandomForestClassifier(max_features=3)\r\n\tmodels['4'] = RandomForestClassifier(max_features=4)\r\n\tmodels['5'] = RandomForestClassifier(max_features=5)\r\n\tmodels['6'] = RandomForestClassifier(max_features=6)\r\n\tmodels['7'] = RandomForestClassifier(max_features=7)\r\n\treturn models\r\n\r\n# evaluate a give model using cross-validation\r\ndef evaluate_model(model):\r\n\tcv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\r\n\tscores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\r\n\treturn scores\r\n\r\n# define dataset\r\nX, y = get_dataset()\r\n# get the models to evaluate\r\nmodels = get_models()\r\n# evaluate the models and store results\r\nresults, names = list(), list()\r\nfor name, model in models.items():\r\n\tscores = evaluate_model(model)\r\n\tresults.append(scores)\r\n\tnames.append(name)\r\n\tprint('&gt;%s %.3f (%.3f)' % (name, mean(scores), std(scores)))\r\n# plot model performance for comparison\r\npyplot.boxplot(results, labels=names, showmeans=True)\r\npyplot.show()<\/pre>\n<p>Running the example first reports the mean accuracy for each feature set size.<\/p>\n<p>In this case, the results suggest that a value between three and five would be appropriate, confirming the sensible default of four on this dataset. A value of five might even be better given the smaller standard deviation in classification accuracy as compared to a value of three or four.<\/p>\n<pre class=\"crayon-plain-tag\">&gt;1 0.897 (0.023)\r\n&gt;2 0.900 (0.028)\r\n&gt;3 0.903 (0.027)\r\n&gt;4 0.903 (0.022)\r\n&gt;5 0.903 (0.019)\r\n&gt;6 0.898 (0.025)\r\n&gt;7 0.900 (0.024)<\/pre>\n<p>A box and whisker plot is created for the distribution of accuracy scores for each feature set size.<\/p>\n<p>We can see a trend in performance rising and peaking with values between three and five and falling again as larger feature set sizes are considered.<\/p>\n<div id=\"attachment_10206\" style=\"width: 1290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-10206\" class=\"size-full wp-image-10206\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Feature-Set-Size-vs-Classification-Accuracy.png\" alt=\"Box Plot of Random Forest Feature Set Size vs. Classification Accuracy\" width=\"1280\" height=\"960\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Feature-Set-Size-vs-Classification-Accuracy.png 1280w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Feature-Set-Size-vs-Classification-Accuracy-300x225.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Feature-Set-Size-vs-Classification-Accuracy-1024x768.png 1024w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Feature-Set-Size-vs-Classification-Accuracy-768x576.png 768w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"><\/p>\n<p id=\"caption-attachment-10206\" class=\"wp-caption-text\">Box Plot of Random Forest Feature Set Size vs. Classification Accuracy<\/p>\n<\/div>\n<h3>Explore Number of Trees<\/h3>\n<p>The number of trees is another key hyperparameter to configure for the random forest.<\/p>\n<p>Typically, the number of trees is increased until the model performance stabilizes. Intuition might suggest that more trees will lead to overfitting, although this is not the case. Both bagging and random forest algorithms appear to be somewhat immune to overfitting the training dataset given the stochastic nature of the learning algorithm.<\/p>\n<p>The number of trees can be set via the &ldquo;<em>n_estimators<\/em>&rdquo; argument and defaults to 100.<\/p>\n<p>The example below explores the effect of the number of trees with values between 10 to 1,000.<\/p>\n<pre class=\"crayon-plain-tag\"># explore random forest number of trees effect on performance\r\nfrom numpy import mean\r\nfrom numpy import std\r\nfrom sklearn.datasets import make_classification\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import RepeatedStratifiedKFold\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom matplotlib import pyplot\r\n\r\n# get the dataset\r\ndef get_dataset():\r\n\tX, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=3)\r\n\treturn X, y\r\n\r\n# get a list of models to evaluate\r\ndef get_models():\r\n\tmodels = dict()\r\n\tmodels['10'] = RandomForestClassifier(n_estimators=10)\r\n\tmodels['50'] = RandomForestClassifier(n_estimators=50)\r\n\tmodels['100'] = RandomForestClassifier(n_estimators=100)\r\n\tmodels['500'] = RandomForestClassifier(n_estimators=500)\r\n\tmodels['1000'] = RandomForestClassifier(n_estimators=1000)\r\n\treturn models\r\n\r\n# evaluate a give model using cross-validation\r\ndef evaluate_model(model):\r\n\tcv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\r\n\tscores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\r\n\treturn scores\r\n\r\n# define dataset\r\nX, y = get_dataset()\r\n# get the models to evaluate\r\nmodels = get_models()\r\n# evaluate the models and store results\r\nresults, names = list(), list()\r\nfor name, model in models.items():\r\n\tscores = evaluate_model(model)\r\n\tresults.append(scores)\r\n\tnames.append(name)\r\n\tprint('&gt;%s %.3f (%.3f)' % (name, mean(scores), std(scores)))\r\n# plot model performance for comparison\r\npyplot.boxplot(results, labels=names, showmeans=True)\r\npyplot.show()<\/pre>\n<p>Running the example first reports the mean accuracy for each configured number of trees.<\/p>\n<p>In this case, we can see that performance rises and stays flat after about 100 trees. Mean accuracy scores fluctuate across 100, 500, and 1,000 trees and this may be statistical noise.<\/p>\n<pre class=\"crayon-plain-tag\">&gt;10 0.870 (0.036)\r\n&gt;50 0.900 (0.028)\r\n&gt;100 0.910 (0.024)\r\n&gt;500 0.904 (0.024)\r\n&gt;1000 0.906 (0.023)<\/pre>\n<p>A box and whisker plot is created for the distribution of accuracy scores for each configured number of trees.<\/p>\n<div id=\"attachment_10207\" style=\"width: 1290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-10207\" class=\"size-full wp-image-10207\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Ensemble-Size-vs-Classification-Accuracy.png\" alt=\"Box Plot of Random Forest Ensemble Size vs. Classification Accuracy\" width=\"1280\" height=\"960\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Ensemble-Size-vs-Classification-Accuracy.png 1280w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Ensemble-Size-vs-Classification-Accuracy-300x225.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Ensemble-Size-vs-Classification-Accuracy-1024x768.png 1024w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Ensemble-Size-vs-Classification-Accuracy-768x576.png 768w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"><\/p>\n<p id=\"caption-attachment-10207\" class=\"wp-caption-text\">Box Plot of Random Forest Ensemble Size vs. Classification Accuracy<\/p>\n<\/div>\n<h3>Explore Tree Depth<\/h3>\n<p>A final interesting hyperparameter is the maximum depth of decision trees used in the ensemble.<\/p>\n<p>By default, trees are constructed to an arbitrary depth and are not pruned. This is a sensible default, although we can also explore fitting trees with different fixed depths.<\/p>\n<p>The maximum tree depth can be specified via the <em>max_depth<\/em> argument and is set to <em>None<\/em> (no maximum depth) by default.<\/p>\n<p>The example below explores the effect of random forest maximum tree depth on model performance.<\/p>\n<pre class=\"crayon-plain-tag\"># explore random forest tree depth effect on performance\r\nfrom numpy import mean\r\nfrom numpy import std\r\nfrom sklearn.datasets import make_classification\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import RepeatedStratifiedKFold\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom matplotlib import pyplot\r\n\r\n# get the dataset\r\ndef get_dataset():\r\n\tX, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=3)\r\n\treturn X, y\r\n\r\n# get a list of models to evaluate\r\ndef get_models():\r\n\tmodels = dict()\r\n\tmodels['1'] = RandomForestClassifier(max_depth=1)\r\n\tmodels['2'] = RandomForestClassifier(max_depth=2)\r\n\tmodels['3'] = RandomForestClassifier(max_depth=3)\r\n\tmodels['4'] = RandomForestClassifier(max_depth=4)\r\n\tmodels['5'] = RandomForestClassifier(max_depth=5)\r\n\tmodels['6'] = RandomForestClassifier(max_depth=6)\r\n\tmodels['7'] = RandomForestClassifier(max_depth=7)\r\n\tmodels['None'] = RandomForestClassifier(max_depth=None)\r\n\treturn models\r\n\r\n# evaluate a give model using cross-validation\r\ndef evaluate_model(model):\r\n\tcv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\r\n\tscores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\r\n\treturn scores\r\n\r\n# define dataset\r\nX, y = get_dataset()\r\n# get the models to evaluate\r\nmodels = get_models()\r\n# evaluate the models and store results\r\nresults, names = list(), list()\r\nfor name, model in models.items():\r\n\tscores = evaluate_model(model)\r\n\tresults.append(scores)\r\n\tnames.append(name)\r\n\tprint('&gt;%s %.3f (%.3f)' % (name, mean(scores), std(scores)))\r\n# plot model performance for comparison\r\npyplot.boxplot(results, labels=names, showmeans=True)\r\npyplot.show()<\/pre>\n<p>Running the example first reports the mean accuracy for each configured maximum tree depth.<\/p>\n<p>In this case, we can see that larger depth results in better model performance, with the default of no maximum depth achieving the best performance on this dataset.<\/p>\n<pre class=\"crayon-plain-tag\">&gt;1 0.771 (0.040)\r\n&gt;2 0.807 (0.037)\r\n&gt;3 0.834 (0.034)\r\n&gt;4 0.857 (0.030)\r\n&gt;5 0.872 (0.025)\r\n&gt;6 0.887 (0.024)\r\n&gt;7 0.890 (0.025)\r\n&gt;None 0.903 (0.027)<\/pre>\n<p>A box and whisker plot is created for the distribution of accuracy scores for each configured maximum tree depth.<\/p>\n<p>In this case, we can see a trend of improved performance with increase in tree depth, supporting the default of no maximum depth.<\/p>\n<div id=\"attachment_10208\" style=\"width: 1290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-10208\" class=\"size-full wp-image-10208\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Maximum-Tree-Depth-vs-Classification-Accuracy.png\" alt=\"Box Plot of Random Forest Maximum Tree Depth vs. Classification Accuracy\" width=\"1280\" height=\"960\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Maximum-Tree-Depth-vs-Classification-Accuracy.png 1280w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Maximum-Tree-Depth-vs-Classification-Accuracy-300x225.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Maximum-Tree-Depth-vs-Classification-Accuracy-1024x768.png 1024w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/04\/Box-Plot-of-Random-Forest-Maximum-Tree-Depth-vs-Classification-Accuracy-768x576.png 768w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"><\/p>\n<p id=\"caption-attachment-10208\" class=\"wp-caption-text\">Box Plot of Random Forest Maximum Tree Depth vs. Classification Accuracy<\/p>\n<\/div>\n<h2>Further Reading<\/h2>\n<p>This section provides more resources on the topic if you are looking to go deeper.<\/p>\n<h3>Tutorials<\/h3>\n<ul>\n<li><a href=\"https:\/\/machinelearningmastery.com\/implement-random-forest-scratch-python\/\">How to Implement Random Forest From Scratch in Python<\/a><\/li>\n<\/ul>\n<h3>Books<\/h3>\n<ul>\n<li><a href=\"https:\/\/amzn.to\/2O3BuOa\">Applied Predictive Modeling<\/a>, 2013.<\/li>\n<li><a href=\"https:\/\/amzn.to\/37xa7DT\">An Introduction to Statistical Learning with Applications in R<\/a>, 2014.<\/li>\n<\/ul>\n<h3>APIs<\/h3>\n<ul>\n<li><a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.ensemble.RandomForestRegressor.html\">sklearn.ensemble.RandomForestRegressor API<\/a>.<\/li>\n<li><a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.ensemble.RandomForestClassifier.html\">sklearn.ensemble.RandomForestClassifier API<\/a>.<\/li>\n<\/ul>\n<h3>Articles<\/h3>\n<ul>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Random_forest\">Random Forest, Wikipedia<\/a>.<\/li>\n<\/ul>\n<h2>Summary<\/h2>\n<p>In this tutorial, you discovered how to develop random forest ensembles for classification and regression.<\/p>\n<p>Specifically, you learned:<\/p>\n<ul>\n<li>Random forest ensemble is an ensemble of decision trees and a natural extension of bagging.<\/li>\n<li>How to use the random forest ensemble for classification and regression with scikit-learn.<\/li>\n<li>How to explore the effect of random forest model hyperparameters on model performance.<\/li>\n<\/ul>\n<p><strong>Do you have any questions?<\/strong><br \/>\nAsk your questions in the comments below and I will do my best to answer.<\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/random-forest-ensemble-in-python\/\">How to Develop a Random Forest Ensemble in Python<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/\">Machine Learning Mastery<\/a>.<\/p>\n<\/div>\n<p><a href=\"https:\/\/machinelearningmastery.com\/random-forest-ensemble-in-python\/\">Go to Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Author: Jason Brownlee Random forest is an ensemble machine learning algorithm. It is perhaps the most popular and widely used machine learning algorithm given its [&hellip;] <span class=\"read-more-link\"><a class=\"read-more\" href=\"https:\/\/www.aiproblog.com\/index.php\/2020\/04\/19\/how-to-develop-a-random-forest-ensemble-in-python\/\">Read More<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":3356,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"footnotes":""},"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/3355"}],"collection":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/comments?post=3355"}],"version-history":[{"count":0,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/3355\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media\/3356"}],"wp:attachment":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media?parent=3355"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/categories?post=3355"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/tags?post=3355"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}