{"id":3663,"date":"2017-07-26T12:46:53","date_gmt":"2017-07-26T11:46:53","guid":{"rendered":"http:\/\/www.blopig.com\/blog\/?p=3663"},"modified":"2017-07-27T00:34:09","modified_gmt":"2017-07-26T23:34:09","slug":"using-random-forests-in-python-with-scikit-learn","status":"publish","type":"post","link":"https:\/\/www.blopig.com\/blog\/2017\/07\/using-random-forests-in-python-with-scikit-learn\/","title":{"rendered":"Using Random Forests in Python with Scikit-Learn"},"content":{"rendered":"<p>I spend a lot of time experimenting with machine learning tools in my research; in particular I seem to spend a lot of time chasing data into random forests and watching the other side to see what comes out. In my many hours of Googling &#8220;random forest foobar&#8221; a disproportionate number of hits offer solutions implemented in R. As a young Pythonista in the present year I find this a thoroughly unacceptable state of affairs, so I decided to write a crash course in how to build random forest models in Python using the machine learning library <a href=\"http:\/\/scikit-learn.org\/stable\/\">scikit-learn<\/a> (or sklearn to friends). This is far from exhaustive, and I won&#8217;t be delving into the machinery of how and why we might want to use a random forest. Rather, the hope is that this will be useful to anyone looking for a hands-on introduction to random forests (or machine learning in general) in Python.<\/p>\n<p>In the future I&#8217;ll write a more in-depth post on how a few libraries turn Python into a powerful environment for data handling and machine learning. Until then, though, let&#8217;s jump into random forests!<\/p>\n<h2>Toy datasets<\/h2>\n<p>Sklearn\u00a0comes with several nicely formatted real-world toy data sets which we can use to experiment with the tools at our disposal. We&#8217;ll be using the\u00a0venerable\u00a0<a href=\"https:\/\/archive.ics.uci.edu\/ml\/datasets\/Iris\/\">iris<\/a> dataset for classification and the <a href=\"http:\/\/lib.stat.cmu.edu\/datasets\/boston\">Boston housing<\/a>\u00a0set for regression. Sklearn comes with a nice selection of data sets and tools for generating synthetic data, all of which are <a href=\"http:\/\/scikit-learn.org\/stable\/datasets\/index.html\">well-documented<\/a>. Now, let&#8217;s write some Python!<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nfrom sklearn import datasets\r\niris = datasets.load_iris()<\/pre>\n<h2>Classification using random forests<\/h2>\n<p>First we&#8217;ll look at how to do solve a simple classification problem using a random forest. The iris dataset is probably the most widely-used example for this problem and nicely illustrates the problem of classification when some classes are not linearly separable from the others.<\/p>\n<p>First we&#8217;ll load the iris dataset into a pandas dataframe. <a href=\"http:\/\/pandas.pydata.org\/\">Pandas<\/a> is a nifty Python library which provides a data structure comparable to the dataframes found in R with database style querying. As an added bonus, the <a href=\"http:\/\/seaborn.pydata.org\/index.html\">seaborn<\/a> visualization library integrates nicely with pandas allowing us to generate a nice scatter matrix of our data with minimal fuss.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">df = pd.DataFrame(iris.data, columns=iris.feature_names)\r\n\r\n# sklearn provides the iris species as integer values since this is required for classification\r\n# here we're just adding a column with the species names to the dataframe for visualisation\r\ndf['species'] = np.array([iris.target_names[i] for i in iris.target])\r\n\r\nsns.pairplot(df, hue='species')<\/pre>\n<p><a href=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/scattermat.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" loading=\"lazy\" class=\"aligncenter wp-image-3666 size-full\" src=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/scattermat.png?resize=625%2C563&#038;ssl=1\" alt=\"\" width=\"625\" height=\"563\" srcset=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/scattermat.png?w=799&amp;ssl=1 799w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/scattermat.png?resize=300%2C270&amp;ssl=1 300w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/scattermat.png?resize=768%2C692&amp;ssl=1 768w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/scattermat.png?resize=624%2C562&amp;ssl=1 624w\" sizes=\"auto, (max-width: 625px) 100vw, 625px\" \/><\/a><\/p>\n<p>Neat. Notice that iris-setosa is easily identifiable by petal length and petal width, while the other two species are much more difficult to distinguish. We could do all sorts of pre-processing and exploratory analysis at this stage, but since this is such a simple dataset let&#8217;s just fire on. We&#8217;ll do a bit of pre-processing later when we come to the Boston data set.<\/p>\n<p>First, let&#8217;s split the data into training and test sets. We&#8217;ll used stratified sampling by iris class to ensure both the training and test sets contain a balanced number of representatives of each of the three classes. Sklearn requires that all features and targets be numeric, so the three classes are represented as integers (0, 1, 2). Here we&#8217;re doing a simple 50\/50 split because the data are so nicely behaved. Typically however we might use a 75\/25 or even 80\/20 training\/test split to ensure we have enough training data. In true Python style this is a one-liner.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from sklearn.model_selection import train_test_split\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(df[iris.feature_names], iris.target, test_size=0.5, stratify=iris.target, random_state=123456)<\/pre>\n<p>Now let&#8217;s fit a random forest classifier to our training set. For the most part we&#8217;ll use the default settings since they&#8217;re quite robust. One exception is the out-of-bag estimate: by default an out-of-bag error estimate is not computed, so we need to tell the classifier object that we want this.<\/p>\n<p>If you&#8217;re used to the R implementation, or you ever find yourself having to compare results using the two, be aware that some parameter names and default settings are different between the two. Fortunately both have excellent documentation so it&#8217;s easy to ensure you&#8217;re using the right parameters if you ever need to compare models.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from sklearn.ensemble import RandomForestClassifier\r\n\r\nrf = RandomForestClassifier(n_estimators=100, oob_score=True, random_state=123456)\r\nrf.fit(X_train, y_train)<\/pre>\n<p>Let&#8217;s see how well our model performs when classifying our unseen test data. For a random forest classifier, the out-of-bag score computed by sklearn is an estimate of the classification accuracy we might expect to observe on new data. We&#8217;ll compare this to the actual score obtained on our test data.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">from sklearn.metrics import accuracy_score\r\n\r\npredicted = rf.predict(X_test)\r\naccuracy = accuracy_score(y_test, predicted)\r\n\r\nprint(f'Out-of-bag score estimate: {rf.oob_score_:.3}')\r\nprint(f'Mean accuracy score: {accuracy:.3}')<\/pre>\n<pre>Out-of-bag score estimate: 0.973\r\nMean accuracy score: 0.933<\/pre>\n<p>Not bad. However, this doesn&#8217;t really tell us anything about where we&#8217;re doing well. A useful technique for visualising performance is the confusion matrix. This is simply a matrix whose diagonal values are true positive counts, while off-diagonal values are false positive and false negative counts for each class against the other.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from sklearn.metrics import confusion_matrix\r\n\r\ncm = pd.DataFrame(confusion_matrix(y_test, predicted), columns=iris.target_names, index=iris.target_names)\r\nsns.heatmap(cm, annot=True)<\/pre>\n<p><a href=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/confmat.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" loading=\"lazy\" class=\"size-full wp-image-3670 aligncenter\" src=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/confmat.png?resize=576%2C396&#038;ssl=1\" alt=\"\" width=\"576\" height=\"396\" srcset=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/confmat.png?w=576&amp;ssl=1 576w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/confmat.png?resize=300%2C206&amp;ssl=1 300w\" sizes=\"auto, (max-width: 576px) 100vw, 576px\" \/><\/a><\/p>\n<p>This\u00a0lets us know\u00a0that our\u00a0model correctly separates the setosa examples, but exhibits a small amount of confusion when attempting to distinguish between versicolor and virginica.<\/p>\n<h2>Random forest regression<\/h2>\n<p>Now let&#8217;s look at using a random forest to solve a regression problem. The Boston housing data set consists of census housing price data in the region of Boston, Massachusetts, together with a series of values quantifying various properties of the local area such as crime rate, air pollution, and student-teacher ratio in schools. The question for us is whether we can use these data to accurately predict median house prices. One caveat of this data set is that the median house price is truncated at $50,000 which suggests that there may be considerable noise in this region of the data. You might want to remove all data with a median house price of $50,000 from the set and see if the regression improves at all.<\/p>\n<p>As before we&#8217;ll load the data into a pandas dataframe. This time, however, we&#8217;re going to do some pre-processing of our data by independently transforming each feature to have zero mean and unit variance. The values of different features vary greatly in order of magnitude. If we were to analyse the raw data as-is, we run the risk of our analysis being skewed by certain features dominating the variance. This isn&#8217;t strictly necessary for a random forest, but will enable us to perform a more meaningful principal component analysis later. Performing this transformation in sklearn is super simple using the StandardScaler class of the preprocessing module. This time we&#8217;re going to use an 80\/20 split of our data. You could bin the house prices to perform stratified sampling, but we won&#8217;t worry about that for now.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">boston = datasets.load_boston()\r\n\r\nfeatures = pd.DataFrame(boston.data, columns=boston.feature_names)\r\ntargets = boston.target<\/pre>\n<p>As before, we&#8217;ve loaded our data into a pandas dataframe. Notice how I have to construct new dataframes from the transformed data. This is because sklearn is built around numpy arrays. While it&#8217;s possible to return a view of a dataframe as an array, transforming the contents of a dataframe requires a little more work. Of course, there&#8217;s a <a href=\"https:\/\/github.com\/pandas-dev\/sklearn-pandas\">library<\/a> for that, but I&#8217;m\u00a0lazy so I didn&#8217;t use it this time.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">from sklearn.preprocessing import StandardScaler\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(features, targets, train_size=0.8, random_state=42)\r\n\r\nscaler = StandardScaler().fit(X_train)\r\nX_train_scaled = pd.DataFrame(scaler.transform(X_train), index=X_train.index.values, columns=X_train.columns.values)\r\nX_test_scaled = pd.DataFrame(scaler.transform(X_test), index=X_test.index.values, columns=X_test.columns.values)\r\n<\/pre>\n<p>With the data standardised, let&#8217;s do a quick principal-component analysis to see if we could reduce the dimensionality of the problem. This is quick and easy in sklearn using the PCA class of the decomposition module.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from sklearn.decomposition import PCA\r\n\r\npca = PCA()\r\npca.fit(X_train)\r\ncpts = pd.DataFrame(pca.transform(X_train))\r\nx_axis = np.arange(1, pca.n_components_+1)\r\npca_scaled = PCA()\r\npca_scaled.fit(X_train_scaled)\r\ncpts_scaled = pd.DataFrame(pca.transform(X_train_scaled))\r\n\r\n# matplotlib boilerplate goes here<\/pre>\n<p><a href=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/pca.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" loading=\"lazy\" class=\"size-full wp-image-3671 aligncenter\" src=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/pca.png?resize=625%2C625&#038;ssl=1\" alt=\"\" width=\"625\" height=\"625\" srcset=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/pca.png?w=720&amp;ssl=1 720w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/pca.png?resize=150%2C150&amp;ssl=1 150w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/pca.png?resize=300%2C300&amp;ssl=1 300w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/pca.png?resize=624%2C624&amp;ssl=1 624w\" sizes=\"auto, (max-width: 625px) 100vw, 625px\" \/><\/a><\/p>\n<p>Notice how without data standardisation the variance is completely dominated by the first principal component. With standardisation, however, we see that in fact we must consider multiple features in order to explain a significant proportion of the variance. You might want to experiment with building regression models using the principal components (or indeed just combinations of the raw features) to see how well you can do with less information. For now though we&#8217;re going to use all of the (scaled) features as the regressors for our model. As with the classification problem fitting the random forest is simple using the RandomForestRegressor class.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from sklearn.ensemble import RandomForestRegressor\r\n\r\nrf = RandomForestRegressor(n_estimators=500, oob_score=True, random_state=0)\r\nrf.fit(X_train, y_train)<\/pre>\n<p>Now let&#8217;s see how we do on our test set. As before we&#8217;ll compare the out-of-bag estimate (this time it&#8217;s an R-squared score) to the R-squared score for our predictions. We&#8217;ll also compute Spearman rank and Pearson correlation coefficients for our predictions to get a feel for how we&#8217;re doing.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from sklearn.metrics import r2_score\r\nfrom scipy.stats import spearmanr, pearsonr\r\n\r\npredicted_train = rf.predict(X_train)\r\npredicted_test = rf.predict(X_test)\r\n\r\ntest_score = r2_score(y_test, predicted_test)\r\nspearman = spearmanr(y_test, predicted_test)\r\npearson = pearsonr(y_test, predicted_test)\r\n\r\nprint(f'Out-of-bag R-2 score estimate: {rf.oob_score_:&gt;5.3}')\r\nprint(f'Test data R-2 score: {test_score:&gt;5.3}')\r\nprint(f'Test data Spearman correlation: {spearman[0]:.3}')\r\nprint(f'Test data Pearson correlation: {pearson[0]:.3}')<\/pre>\n<pre>Out-of-bag R-2 score estimate: 0.841\r\nTest data R-2 score: 0.886\r\nTest data Spearman correlation: 0.904\r\nTest data Pearson correlation: 0.942<\/pre>\n<p><a href=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/regression.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" loading=\"lazy\" class=\"size-full wp-image-3673 aligncenter\" src=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/regression.png?resize=360%2C360&#038;ssl=1\" alt=\"\" width=\"360\" height=\"360\" srcset=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/regression.png?w=360&amp;ssl=1 360w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/regression.png?resize=150%2C150&amp;ssl=1 150w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/07\/regression.png?resize=300%2C300&amp;ssl=1 300w\" sizes=\"auto, (max-width: 360px) 100vw, 360px\" \/><\/a><\/p>\n<p>Not too bad, though there are a few outliers that would be worth looking into. Your challenge, should you choose to accept it, is to see if removing the $50,000 data improves the regression.<\/p>\n<h2>Wrapping up<\/h2>\n<p>Congratulations on making it this far. Now you know how to pre-process your data and build random forest models all from the comfort of your iPython session. I plan on writing more in the future about how to use Python for machine learning, and in particular how to make use of some of the powerful tools available in sklearn (a pipeline for data preparation, model fitting, prediction, in one line of Python? Yes please!), and how to make sklearn and pandas play nicely with minimal hassle. If you&#8217;re lucky, and if I can bring myself to process the data nicely, I might include some fun examples from less well-behaved real-world data sets.<\/p>\n<p>Until then, though, happy Pythoning!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I spend a lot of time experimenting with machine learning tools in my research; in particular I seem to spend a lot of time chasing data into random forests and watching the other side to see what comes out. In my many hours of Googling &#8220;random forest foobar&#8221; a disproportionate number of hits offer solutions [&hellip;]<\/p>\n","protected":false},"author":47,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","wikipediapreview_detectlinks":true,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"ngg_post_thumbnail":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[29,14],"tags":[172,152,173,174],"ppma_author":[498],"class_list":["post-3663","post","type-post","status-publish","format-standard","hentry","category-code","category-howto","tag-machine-learning","tag-python","tag-random-forest","tag-scikit-learn"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"authors":[{"term_id":498,"user_id":47,"is_guest":0,"slug":"fergus","display_name":"Fergus Boyles","avatar_url":"https:\/\/secure.gravatar.com\/avatar\/ba8c419ba77128aad589b66ba7ee13da74f4ce2d3108fd724ddcefa200b51c7b?s=96&d=mm&r=g","0":null,"1":"","2":"","3":"","4":"","5":"","6":"","7":"","8":""}],"_links":{"self":[{"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/posts\/3663","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/users\/47"}],"replies":[{"embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/comments?post=3663"}],"version-history":[{"count":14,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/posts\/3663\/revisions"}],"predecessor-version":[{"id":3679,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/posts\/3663\/revisions\/3679"}],"wp:attachment":[{"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/media?parent=3663"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/categories?post=3663"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/tags?post=3663"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/ppma_author?post=3663"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}