<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Ensembles - MLlib - Spark 1.4.1 Documentation</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
body {
padding-top: 60px;
padding-bottom: 40px;
}
</style>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/bootstrap-responsive.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.1-respond-1.1.0.min.js"></script>
<link rel="stylesheet" href="css/pygments-default.css">
<!-- Google analytics script -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-32518208-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an outdated browser. <a href="http://browsehappy.com/">Upgrade your browser today</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to better experience this site.</p>
<![endif]-->
<!-- This code is taken from http://twitter.github.com/bootstrap/examples/hero.html -->
<div class="navbar navbar-fixed-top" id="topbar">
<div class="navbar-inner">
<div class="container">
<div class="brand"><a href="index.html">
<img src="img/spark-logo-hd.png" style="height:50px;"/></a><span class="version">1.4.1</span>
</div>
<ul class="nav">
<!--TODO(andyk): Add class="active" attribute to li some how.-->
<li><a href="index.html">Overview</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Programming Guides<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="quick-start.html">Quick Start</a></li>
<li><a href="programming-guide.html">Spark Programming Guide</a></li>
<li class="divider"></li>
<li><a href="streaming-programming-guide.html">Spark Streaming</a></li>
<li><a href="sql-programming-guide.html">DataFrames and SQL</a></li>
<li><a href="mllib-guide.html">MLlib (Machine Learning)</a></li>
<li><a href="graphx-programming-guide.html">GraphX (Graph Processing)</a></li>
<li><a href="bagel-programming-guide.html">Bagel (Pregel on Spark)</a></li>
<li><a href="sparkr.html">SparkR (R on Spark)</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Docs<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="api/scala/index.html#org.apache.spark.package">Scala</a></li>
<li><a href="api/java/index.html">Java</a></li>
<li><a href="api/python/index.html">Python</a></li>
<li><a href="api/R/index.html">R</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Deploying<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="cluster-overview.html">Overview</a></li>
<li><a href="submitting-applications.html">Submitting Applications</a></li>
<li class="divider"></li>
<li><a href="spark-standalone.html">Spark Standalone</a></li>
<li><a href="running-on-mesos.html">Mesos</a></li>
<li><a href="running-on-yarn.html">YARN</a></li>
<li class="divider"></li>
<li><a href="ec2-scripts.html">Amazon EC2</a></li>
</ul>
</li>
<li class="dropdown">
<a href="api.html" class="dropdown-toggle" data-toggle="dropdown">More<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="configuration.html">Configuration</a></li>
<li><a href="monitoring.html">Monitoring</a></li>
<li><a href="tuning.html">Tuning Guide</a></li>
<li><a href="job-scheduling.html">Job Scheduling</a></li>
<li><a href="security.html">Security</a></li>
<li><a href="hardware-provisioning.html">Hardware Provisioning</a></li>
<li><a href="hadoop-third-party-distributions.html">3<sup>rd</sup>-Party Hadoop Distros</a></li>
<li class="divider"></li>
<li><a href="building-spark.html">Building Spark</a></li>
<li><a href="https://cwiki.apache.org/confluence/display/SPARK/Contributing+to+Spark">Contributing to Spark</a></li>
<li><a href="https://cwiki.apache.org/confluence/display/SPARK/Supplemental+Spark+Projects">Supplemental Projects</a></li>
</ul>
</li>
</ul>
<!--<p class="navbar-text pull-right"><span class="version-text">v1.4.1</span></p>-->
</div>
</div>
</div>
<div class="container" id="content">
<h1 class="title"><a href="mllib-guide.html">MLlib</a> - Ensembles</h1>
<ul id="markdown-toc">
<li><a href="#gradient-boosted-trees-vs-random-forests" id="markdown-toc-gradient-boosted-trees-vs-random-forests">Gradient-Boosted Trees vs. Random Forests</a></li>
<li><a href="#random-forests" id="markdown-toc-random-forests">Random Forests</a> <ul>
<li><a href="#basic-algorithm" id="markdown-toc-basic-algorithm">Basic algorithm</a> <ul>
<li><a href="#training" id="markdown-toc-training">Training</a></li>
<li><a href="#prediction" id="markdown-toc-prediction">Prediction</a></li>
</ul>
</li>
<li><a href="#usage-tips" id="markdown-toc-usage-tips">Usage tips</a></li>
<li><a href="#examples" id="markdown-toc-examples">Examples</a> <ul>
<li><a href="#classification" id="markdown-toc-classification">Classification</a></li>
<li><a href="#regression" id="markdown-toc-regression">Regression</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#gradient-boosted-trees-gbts" id="markdown-toc-gradient-boosted-trees-gbts">Gradient-Boosted Trees (GBTs)</a> <ul>
<li><a href="#basic-algorithm-1" id="markdown-toc-basic-algorithm-1">Basic algorithm</a> <ul>
<li><a href="#losses" id="markdown-toc-losses">Losses</a></li>
</ul>
</li>
<li><a href="#usage-tips-1" id="markdown-toc-usage-tips-1">Usage tips</a> <ul>
<li><a href="#validation-while-training" id="markdown-toc-validation-while-training">Validation while training</a></li>
</ul>
</li>
<li><a href="#examples-1" id="markdown-toc-examples-1">Examples</a> <ul>
<li><a href="#classification-1" id="markdown-toc-classification-1">Classification</a></li>
<li><a href="#regression-1" id="markdown-toc-regression-1">Regression</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<p>An <a href="http://en.wikipedia.org/wiki/Ensemble_learning">ensemble method</a>
is a learning algorithm which creates a model composed of a set of other base models.
MLlib supports two major ensemble algorithms: <a href="api/scala/index.html#org.apache.spark.mllib.tree.GradientBosotedTrees"><code>GradientBoostedTrees</code></a> and <a href="api/scala/index.html#org.apache.spark.mllib.tree.RandomForest"><code>RandomForest</code></a>.
Both use <a href="mllib-decision-tree.html">decision trees</a> as their base models.</p>
<h2 id="gradient-boosted-trees-vs-random-forests">Gradient-Boosted Trees vs. Random Forests</h2>
<p>Both <a href="mllib-ensembles.html#Gradient-Boosted-Trees-(GBTS)">Gradient-Boosted Trees (GBTs)</a> and <a href="mllib-ensembles.html#Random-Forests">Random Forests</a> are algorithms for learning ensembles of trees, but the training processes are different. There are several practical trade-offs:</p>
<ul>
<li>GBTs train one tree at a time, so they can take longer to train than random forests. Random Forests can train multiple trees in parallel.
<ul>
<li>On the other hand, it is often reasonable to use smaller (shallower) trees with GBTs than with Random Forests, and training smaller trees takes less time.</li>
</ul>
</li>
<li>Random Forests can be less prone to overfitting. Training more trees in a Random Forest reduces the likelihood of overfitting, but training more trees with GBTs increases the likelihood of overfitting. (In statistical language, Random Forests reduce variance by using more trees, whereas GBTs reduce bias by using more trees.)</li>
<li>Random Forests can be easier to tune since performance improves monotonically with the number of trees (whereas performance can start to decrease for GBTs if the number of trees grows too large).</li>
</ul>
<p>In short, both algorithms can be effective, and the choice should be based on the particular dataset.</p>
<h2 id="random-forests">Random Forests</h2>
<p><a href="http://en.wikipedia.org/wiki/Random_forest">Random forests</a>
are ensembles of <a href="mllib-decision-tree.html">decision trees</a>.
Random forests are one of the most successful machine learning models for classification and
regression. They combine many decision trees in order to reduce the risk of overfitting.
Like decision trees, random forests handle categorical features,
extend to the multiclass classification setting, do not require
feature scaling, and are able to capture non-linearities and feature interactions.</p>
<p>MLlib supports random forests for binary and multiclass classification and for regression,
using both continuous and categorical features.
MLlib implements random forests using the existing <a href="mllib-decision-tree.html">decision tree</a>
implementation. Please see the decision tree guide for more information on trees.</p>
<h3 id="basic-algorithm">Basic algorithm</h3>
<p>Random forests train a set of decision trees separately, so the training can be done in parallel.
The algorithm injects randomness into the training process so that each decision tree is a bit
different. Combining the predictions from each tree reduces the variance of the predictions,
improving the performance on test data.</p>
<h4 id="training">Training</h4>
<p>The randomness injected into the training process includes:</p>
<ul>
<li>Subsampling the original dataset on each iteration to get a different training set (a.k.a. bootstrapping).</li>
<li>Considering different random subsets of features to split on at each tree node.</li>
</ul>
<p>Apart from these randomizations, decision tree training is done in the same way as for individual decision trees.</p>
<h4 id="prediction">Prediction</h4>
<p>To make a prediction on a new instance, a random forest must aggregate the predictions from its set of decision trees. This aggregation is done differently for classification and regression.</p>
<p><em>Classification</em>: Majority vote. Each tree’s prediction is counted as a vote for one class. The label is predicted to be the class which receives the most votes.</p>
<p><em>Regression</em>: Averaging. Each tree predicts a real value. The label is predicted to be the average of the tree predictions.</p>
<h3 id="usage-tips">Usage tips</h3>
<p>We include a few guidelines for using random forests by discussing the various parameters.
We omit some decision tree parameters since those are covered in the <a href="mllib-decision-tree.html">decision tree guide</a>.</p>
<p>The first two parameters we mention are the most important, and tuning them can often improve performance:</p>
<ul>
<li><strong><code>numTrees</code></strong>: Number of trees in the forest.
<ul>
<li>Increasing the number of trees will decrease the variance in predictions, improving the model’s test-time accuracy.</li>
<li>Training time increases roughly linearly in the number of trees.</li>
</ul>
</li>
<li><strong><code>maxDepth</code></strong>: Maximum depth of each tree in the forest.
<ul>
<li>Increasing the depth makes the model more expressive and powerful. However, deep trees take longer to train and are also more prone to overfitting.</li>
<li>In general, it is acceptable to train deeper trees when using random forests than when using a single decision tree. One tree is more likely to overfit than a random forest (because of the variance reduction from averaging multiple trees in the forest).</li>
</ul>
</li>
</ul>
<p>The next two parameters generally do not require tuning. However, they can be tuned to speed up training.</p>
<ul>
<li>
<p><strong><code>subsamplingRate</code></strong>: This parameter specifies the size of the dataset used for training each tree in the forest, as a fraction of the size of the original dataset. The default (1.0) is recommended, but decreasing this fraction can speed up training.</p>
</li>
<li>
<p><strong><code>featureSubsetStrategy</code></strong>: Number of features to use as candidates for splitting at each tree node. The number is specified as a fraction or function of the total number of features. Decreasing this number will speed up training, but can sometimes impact performance if too low.</p>
</li>
</ul>
<h3 id="examples">Examples</h3>
<h4 id="classification">Classification</h4>
<p>The example below demonstrates how to load a
<a href="http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/">LIBSVM data file</a>,
parse it as an RDD of <code>LabeledPoint</code> and then
perform classification using a Random Forest.
The test error is calculated to measure the algorithm accuracy.</p>
<div class="codetabs">
<div data-lang="scala">
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.RandomForest</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.model.RandomForestModel</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.util.MLUtils</span>
<span class="c1">// Load and parse the data file.</span>
<span class="k">val</span> <span class="n">data</span> <span class="k">=</span> <span class="nc">MLUtils</span><span class="o">.</span><span class="n">loadLibSVMFile</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="o">)</span>
<span class="c1">// Split the data into training and test sets (30% held out for testing)</span>
<span class="k">val</span> <span class="n">splits</span> <span class="k">=</span> <span class="n">data</span><span class="o">.</span><span class="n">randomSplit</span><span class="o">(</span><span class="nc">Array</span><span class="o">(</span><span class="mf">0.7</span><span class="o">,</span> <span class="mf">0.3</span><span class="o">))</span>
<span class="k">val</span> <span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">testData</span><span class="o">)</span> <span class="k">=</span> <span class="o">(</span><span class="n">splits</span><span class="o">(</span><span class="mi">0</span><span class="o">),</span> <span class="n">splits</span><span class="o">(</span><span class="mi">1</span><span class="o">))</span>
<span class="c1">// Train a RandomForest model.</span>
<span class="c1">// Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="k">val</span> <span class="n">numClasses</span> <span class="k">=</span> <span class="mi">2</span>
<span class="k">val</span> <span class="n">categoricalFeaturesInfo</span> <span class="k">=</span> <span class="nc">Map</span><span class="o">[</span><span class="kt">Int</span>, <span class="kt">Int</span><span class="o">]()</span>
<span class="k">val</span> <span class="n">numTrees</span> <span class="k">=</span> <span class="mi">3</span> <span class="c1">// Use more in practice.</span>
<span class="k">val</span> <span class="n">featureSubsetStrategy</span> <span class="k">=</span> <span class="s">"auto"</span> <span class="c1">// Let the algorithm choose.</span>
<span class="k">val</span> <span class="n">impurity</span> <span class="k">=</span> <span class="s">"gini"</span>
<span class="k">val</span> <span class="n">maxDepth</span> <span class="k">=</span> <span class="mi">4</span>
<span class="k">val</span> <span class="n">maxBins</span> <span class="k">=</span> <span class="mi">32</span>
<span class="k">val</span> <span class="n">model</span> <span class="k">=</span> <span class="nc">RandomForest</span><span class="o">.</span><span class="n">trainClassifier</span><span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">numClasses</span><span class="o">,</span> <span class="n">categoricalFeaturesInfo</span><span class="o">,</span>
<span class="n">numTrees</span><span class="o">,</span> <span class="n">featureSubsetStrategy</span><span class="o">,</span> <span class="n">impurity</span><span class="o">,</span> <span class="n">maxDepth</span><span class="o">,</span> <span class="n">maxBins</span><span class="o">)</span>
<span class="c1">// Evaluate model on test instances and compute test error</span>
<span class="k">val</span> <span class="n">labelAndPreds</span> <span class="k">=</span> <span class="n">testData</span><span class="o">.</span><span class="n">map</span> <span class="o">{</span> <span class="n">point</span> <span class="k">=></span>
<span class="k">val</span> <span class="n">prediction</span> <span class="k">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="o">(</span><span class="n">point</span><span class="o">.</span><span class="n">features</span><span class="o">)</span>
<span class="o">(</span><span class="n">point</span><span class="o">.</span><span class="n">label</span><span class="o">,</span> <span class="n">prediction</span><span class="o">)</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">testErr</span> <span class="k">=</span> <span class="n">labelAndPreds</span><span class="o">.</span><span class="n">filter</span><span class="o">(</span><span class="n">r</span> <span class="k">=></span> <span class="n">r</span><span class="o">.</span><span class="n">_1</span> <span class="o">!=</span> <span class="n">r</span><span class="o">.</span><span class="n">_2</span><span class="o">).</span><span class="n">count</span><span class="o">.</span><span class="n">toDouble</span> <span class="o">/</span> <span class="n">testData</span><span class="o">.</span><span class="n">count</span><span class="o">()</span>
<span class="n">println</span><span class="o">(</span><span class="s">"Test Error = "</span> <span class="o">+</span> <span class="n">testErr</span><span class="o">)</span>
<span class="n">println</span><span class="o">(</span><span class="s">"Learned classification forest model:\n"</span> <span class="o">+</span> <span class="n">model</span><span class="o">.</span><span class="n">toDebugString</span><span class="o">)</span>
<span class="c1">// Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="n">save</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"myModelPath"</span><span class="o">)</span>
<span class="k">val</span> <span class="n">sameModel</span> <span class="k">=</span> <span class="nc">RandomForestModel</span><span class="o">.</span><span class="n">load</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"myModelPath"</span><span class="o">)</span></code></pre></div>
</div>
<div data-lang="java">
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">scala.Tuple2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.HashMap</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.SparkConf</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaPairRDD</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaRDD</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaSparkContext</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.Function</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.PairFunction</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.regression.LabeledPoint</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.RandomForest</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.model.RandomForestModel</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.util.MLUtils</span><span class="o">;</span>
<span class="n">SparkConf</span> <span class="n">sparkConf</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">SparkConf</span><span class="o">().</span><span class="na">setAppName</span><span class="o">(</span><span class="s">"JavaRandomForestClassification"</span><span class="o">);</span>
<span class="n">JavaSparkContext</span> <span class="n">sc</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">JavaSparkContext</span><span class="o">(</span><span class="n">sparkConf</span><span class="o">);</span>
<span class="c1">// Load and parse the data file.</span>
<span class="n">String</span> <span class="n">datapath</span> <span class="o">=</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="o">;</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">data</span> <span class="o">=</span> <span class="n">MLUtils</span><span class="o">.</span><span class="na">loadLibSVMFile</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="n">datapath</span><span class="o">).</span><span class="na">toJavaRDD</span><span class="o">();</span>
<span class="c1">// Split the data into training and test sets (30% held out for testing)</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">>[]</span> <span class="n">splits</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="na">randomSplit</span><span class="o">(</span><span class="k">new</span> <span class="kt">double</span><span class="o">[]{</span><span class="mf">0.7</span><span class="o">,</span> <span class="mf">0.3</span><span class="o">});</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">trainingData</span> <span class="o">=</span> <span class="n">splits</span><span class="o">[</span><span class="mi">0</span><span class="o">];</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">testData</span> <span class="o">=</span> <span class="n">splits</span><span class="o">[</span><span class="mi">1</span><span class="o">];</span>
<span class="c1">// Train a RandomForest model.</span>
<span class="c1">// Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="n">Integer</span> <span class="n">numClasses</span> <span class="o">=</span> <span class="mi">2</span><span class="o">;</span>
<span class="n">HashMap</span><span class="o"><</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">></span> <span class="n">categoricalFeaturesInfo</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o"><</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">>();</span>
<span class="n">Integer</span> <span class="n">numTrees</span> <span class="o">=</span> <span class="mi">3</span><span class="o">;</span> <span class="c1">// Use more in practice.</span>
<span class="n">String</span> <span class="n">featureSubsetStrategy</span> <span class="o">=</span> <span class="s">"auto"</span><span class="o">;</span> <span class="c1">// Let the algorithm choose.</span>
<span class="n">String</span> <span class="n">impurity</span> <span class="o">=</span> <span class="s">"gini"</span><span class="o">;</span>
<span class="n">Integer</span> <span class="n">maxDepth</span> <span class="o">=</span> <span class="mi">5</span><span class="o">;</span>
<span class="n">Integer</span> <span class="n">maxBins</span> <span class="o">=</span> <span class="mi">32</span><span class="o">;</span>
<span class="n">Integer</span> <span class="n">seed</span> <span class="o">=</span> <span class="mi">12345</span><span class="o">;</span>
<span class="kd">final</span> <span class="n">RandomForestModel</span> <span class="n">model</span> <span class="o">=</span> <span class="n">RandomForest</span><span class="o">.</span><span class="na">trainClassifier</span><span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">numClasses</span><span class="o">,</span>
<span class="n">categoricalFeaturesInfo</span><span class="o">,</span> <span class="n">numTrees</span><span class="o">,</span> <span class="n">featureSubsetStrategy</span><span class="o">,</span> <span class="n">impurity</span><span class="o">,</span> <span class="n">maxDepth</span><span class="o">,</span> <span class="n">maxBins</span><span class="o">,</span>
<span class="n">seed</span><span class="o">);</span>
<span class="c1">// Evaluate model on test instances and compute test error</span>
<span class="n">JavaPairRDD</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="n">predictionAndLabel</span> <span class="o">=</span>
<span class="n">testData</span><span class="o">.</span><span class="na">mapToPair</span><span class="o">(</span><span class="k">new</span> <span class="n">PairFunction</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">,</span> <span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="nf">call</span><span class="o">(</span><span class="n">LabeledPoint</span> <span class="n">p</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>(</span><span class="n">model</span><span class="o">.</span><span class="na">predict</span><span class="o">(</span><span class="n">p</span><span class="o">.</span><span class="na">features</span><span class="o">()),</span> <span class="n">p</span><span class="o">.</span><span class="na">label</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">});</span>
<span class="n">Double</span> <span class="n">testErr</span> <span class="o">=</span>
<span class="mf">1.0</span> <span class="o">*</span> <span class="n">predictionAndLabel</span><span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="k">new</span> <span class="n">Function</span><span class="o"><</span><span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>,</span> <span class="n">Boolean</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Boolean</span> <span class="nf">call</span><span class="o">(</span><span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="n">pl</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="o">!</span><span class="n">pl</span><span class="o">.</span><span class="na">_1</span><span class="o">().</span><span class="na">equals</span><span class="o">(</span><span class="n">pl</span><span class="o">.</span><span class="na">_2</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}).</span><span class="na">count</span><span class="o">()</span> <span class="o">/</span> <span class="n">testData</span><span class="o">.</span><span class="na">count</span><span class="o">();</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Test Error: "</span> <span class="o">+</span> <span class="n">testErr</span><span class="o">);</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Learned classification forest model:\n"</span> <span class="o">+</span> <span class="n">model</span><span class="o">.</span><span class="na">toDebugString</span><span class="o">());</span>
<span class="c1">// Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="na">save</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="s">"myModelPath"</span><span class="o">);</span>
<span class="n">RandomForestModel</span> <span class="n">sameModel</span> <span class="o">=</span> <span class="n">RandomForestModel</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="s">"myModelPath"</span><span class="o">);</span></code></pre></div>
</div>
<div data-lang="python">
<div class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">pyspark.mllib.tree</span> <span class="kn">import</span> <span class="n">RandomForest</span><span class="p">,</span> <span class="n">RandomForestModel</span>
<span class="kn">from</span> <span class="nn">pyspark.mllib.util</span> <span class="kn">import</span> <span class="n">MLUtils</span>
<span class="c"># Load and parse the data file into an RDD of LabeledPoint.</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">MLUtils</span><span class="o">.</span><span class="n">loadLibSVMFile</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">'data/mllib/sample_libsvm_data.txt'</span><span class="p">)</span>
<span class="c"># Split the data into training and test sets (30% held out for testing)</span>
<span class="p">(</span><span class="n">trainingData</span><span class="p">,</span> <span class="n">testData</span><span class="p">)</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">randomSplit</span><span class="p">([</span><span class="mf">0.7</span><span class="p">,</span> <span class="mf">0.3</span><span class="p">])</span>
<span class="c"># Train a RandomForest model.</span>
<span class="c"># Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="c"># Note: Use larger numTrees in practice.</span>
<span class="c"># Setting featureSubsetStrategy="auto" lets the algorithm choose.</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">RandomForest</span><span class="o">.</span><span class="n">trainClassifier</span><span class="p">(</span><span class="n">trainingData</span><span class="p">,</span> <span class="n">numClasses</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">categoricalFeaturesInfo</span><span class="o">=</span><span class="p">{},</span>
<span class="n">numTrees</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">featureSubsetStrategy</span><span class="o">=</span><span class="s">"auto"</span><span class="p">,</span>
<span class="n">impurity</span><span class="o">=</span><span class="s">'gini'</span><span class="p">,</span> <span class="n">maxDepth</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">maxBins</span><span class="o">=</span><span class="mi">32</span><span class="p">)</span>
<span class="c"># Evaluate model on test instances and compute test error</span>
<span class="n">predictions</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">testData</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">features</span><span class="p">))</span>
<span class="n">labelsAndPredictions</span> <span class="o">=</span> <span class="n">testData</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">lp</span><span class="p">:</span> <span class="n">lp</span><span class="o">.</span><span class="n">label</span><span class="p">)</span><span class="o">.</span><span class="n">zip</span><span class="p">(</span><span class="n">predictions</span><span class="p">)</span>
<span class="n">testErr</span> <span class="o">=</span> <span class="n">labelsAndPredictions</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">p</span><span class="p">):</span> <span class="n">v</span> <span class="o">!=</span> <span class="n">p</span><span class="p">)</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">testData</span><span class="o">.</span><span class="n">count</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Test Error = '</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">testErr</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Learned classification forest model:'</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">toDebugString</span><span class="p">())</span>
<span class="c"># Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"myModelPath"</span><span class="p">)</span>
<span class="n">sameModel</span> <span class="o">=</span> <span class="n">RandomForestModel</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"myModelPath"</span><span class="p">)</span></code></pre></div>
</div>
</div>
<h4 id="regression">Regression</h4>
<p>The example below demonstrates how to load a
<a href="http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/">LIBSVM data file</a>,
parse it as an RDD of <code>LabeledPoint</code> and then
perform regression using a Random Forest.
The Mean Squared Error (MSE) is computed at the end to evaluate
<a href="http://en.wikipedia.org/wiki/Goodness_of_fit">goodness of fit</a>.</p>
<div class="codetabs">
<div data-lang="scala">
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.RandomForest</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.model.RandomForestModel</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.util.MLUtils</span>
<span class="c1">// Load and parse the data file.</span>
<span class="k">val</span> <span class="n">data</span> <span class="k">=</span> <span class="nc">MLUtils</span><span class="o">.</span><span class="n">loadLibSVMFile</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="o">)</span>
<span class="c1">// Split the data into training and test sets (30% held out for testing)</span>
<span class="k">val</span> <span class="n">splits</span> <span class="k">=</span> <span class="n">data</span><span class="o">.</span><span class="n">randomSplit</span><span class="o">(</span><span class="nc">Array</span><span class="o">(</span><span class="mf">0.7</span><span class="o">,</span> <span class="mf">0.3</span><span class="o">))</span>
<span class="k">val</span> <span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">testData</span><span class="o">)</span> <span class="k">=</span> <span class="o">(</span><span class="n">splits</span><span class="o">(</span><span class="mi">0</span><span class="o">),</span> <span class="n">splits</span><span class="o">(</span><span class="mi">1</span><span class="o">))</span>
<span class="c1">// Train a RandomForest model.</span>
<span class="c1">// Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="k">val</span> <span class="n">numClasses</span> <span class="k">=</span> <span class="mi">2</span>
<span class="k">val</span> <span class="n">categoricalFeaturesInfo</span> <span class="k">=</span> <span class="nc">Map</span><span class="o">[</span><span class="kt">Int</span>, <span class="kt">Int</span><span class="o">]()</span>
<span class="k">val</span> <span class="n">numTrees</span> <span class="k">=</span> <span class="mi">3</span> <span class="c1">// Use more in practice.</span>
<span class="k">val</span> <span class="n">featureSubsetStrategy</span> <span class="k">=</span> <span class="s">"auto"</span> <span class="c1">// Let the algorithm choose.</span>
<span class="k">val</span> <span class="n">impurity</span> <span class="k">=</span> <span class="s">"variance"</span>
<span class="k">val</span> <span class="n">maxDepth</span> <span class="k">=</span> <span class="mi">4</span>
<span class="k">val</span> <span class="n">maxBins</span> <span class="k">=</span> <span class="mi">32</span>
<span class="k">val</span> <span class="n">model</span> <span class="k">=</span> <span class="nc">RandomForest</span><span class="o">.</span><span class="n">trainRegressor</span><span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">categoricalFeaturesInfo</span><span class="o">,</span>
<span class="n">numTrees</span><span class="o">,</span> <span class="n">featureSubsetStrategy</span><span class="o">,</span> <span class="n">impurity</span><span class="o">,</span> <span class="n">maxDepth</span><span class="o">,</span> <span class="n">maxBins</span><span class="o">)</span>
<span class="c1">// Evaluate model on test instances and compute test error</span>
<span class="k">val</span> <span class="n">labelsAndPredictions</span> <span class="k">=</span> <span class="n">testData</span><span class="o">.</span><span class="n">map</span> <span class="o">{</span> <span class="n">point</span> <span class="k">=></span>
<span class="k">val</span> <span class="n">prediction</span> <span class="k">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="o">(</span><span class="n">point</span><span class="o">.</span><span class="n">features</span><span class="o">)</span>
<span class="o">(</span><span class="n">point</span><span class="o">.</span><span class="n">label</span><span class="o">,</span> <span class="n">prediction</span><span class="o">)</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">testMSE</span> <span class="k">=</span> <span class="n">labelsAndPredictions</span><span class="o">.</span><span class="n">map</span><span class="o">{</span> <span class="k">case</span><span class="o">(</span><span class="n">v</span><span class="o">,</span> <span class="n">p</span><span class="o">)</span> <span class="k">=></span> <span class="n">math</span><span class="o">.</span><span class="n">pow</span><span class="o">((</span><span class="n">v</span> <span class="o">-</span> <span class="n">p</span><span class="o">),</span> <span class="mi">2</span><span class="o">)}.</span><span class="n">mean</span><span class="o">()</span>
<span class="n">println</span><span class="o">(</span><span class="s">"Test Mean Squared Error = "</span> <span class="o">+</span> <span class="n">testMSE</span><span class="o">)</span>
<span class="n">println</span><span class="o">(</span><span class="s">"Learned regression forest model:\n"</span> <span class="o">+</span> <span class="n">model</span><span class="o">.</span><span class="n">toDebugString</span><span class="o">)</span>
<span class="c1">// Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="n">save</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"myModelPath"</span><span class="o">)</span>
<span class="k">val</span> <span class="n">sameModel</span> <span class="k">=</span> <span class="nc">RandomForestModel</span><span class="o">.</span><span class="n">load</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"myModelPath"</span><span class="o">)</span></code></pre></div>
</div>
<div data-lang="java">
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">java.util.HashMap</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">scala.Tuple2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.Function2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaPairRDD</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaRDD</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaSparkContext</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.Function</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.PairFunction</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.regression.LabeledPoint</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.RandomForest</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.model.RandomForestModel</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.util.MLUtils</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.SparkConf</span><span class="o">;</span>
<span class="n">SparkConf</span> <span class="n">sparkConf</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">SparkConf</span><span class="o">().</span><span class="na">setAppName</span><span class="o">(</span><span class="s">"JavaRandomForest"</span><span class="o">);</span>
<span class="n">JavaSparkContext</span> <span class="n">sc</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">JavaSparkContext</span><span class="o">(</span><span class="n">sparkConf</span><span class="o">);</span>
<span class="c1">// Load and parse the data file.</span>
<span class="n">String</span> <span class="n">datapath</span> <span class="o">=</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="o">;</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">data</span> <span class="o">=</span> <span class="n">MLUtils</span><span class="o">.</span><span class="na">loadLibSVMFile</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="n">datapath</span><span class="o">).</span><span class="na">toJavaRDD</span><span class="o">();</span>
<span class="c1">// Split the data into training and test sets (30% held out for testing)</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">>[]</span> <span class="n">splits</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="na">randomSplit</span><span class="o">(</span><span class="k">new</span> <span class="kt">double</span><span class="o">[]{</span><span class="mf">0.7</span><span class="o">,</span> <span class="mf">0.3</span><span class="o">});</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">trainingData</span> <span class="o">=</span> <span class="n">splits</span><span class="o">[</span><span class="mi">0</span><span class="o">];</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">testData</span> <span class="o">=</span> <span class="n">splits</span><span class="o">[</span><span class="mi">1</span><span class="o">];</span>
<span class="c1">// Set parameters.</span>
<span class="c1">// Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="n">Map</span><span class="o"><</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">></span> <span class="n">categoricalFeaturesInfo</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o"><</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">>();</span>
<span class="n">String</span> <span class="n">impurity</span> <span class="o">=</span> <span class="s">"variance"</span><span class="o">;</span>
<span class="n">Integer</span> <span class="n">maxDepth</span> <span class="o">=</span> <span class="mi">4</span><span class="o">;</span>
<span class="n">Integer</span> <span class="n">maxBins</span> <span class="o">=</span> <span class="mi">32</span><span class="o">;</span>
<span class="c1">// Train a RandomForest model.</span>
<span class="kd">final</span> <span class="n">RandomForestModel</span> <span class="n">model</span> <span class="o">=</span> <span class="n">RandomForest</span><span class="o">.</span><span class="na">trainRegressor</span><span class="o">(</span><span class="n">trainingData</span><span class="o">,</span>
<span class="n">categoricalFeaturesInfo</span><span class="o">,</span> <span class="n">impurity</span><span class="o">,</span> <span class="n">maxDepth</span><span class="o">,</span> <span class="n">maxBins</span><span class="o">);</span>
<span class="c1">// Evaluate model on test instances and compute test error</span>
<span class="n">JavaPairRDD</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="n">predictionAndLabel</span> <span class="o">=</span>
<span class="n">testData</span><span class="o">.</span><span class="na">mapToPair</span><span class="o">(</span><span class="k">new</span> <span class="n">PairFunction</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">,</span> <span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="nf">call</span><span class="o">(</span><span class="n">LabeledPoint</span> <span class="n">p</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>(</span><span class="n">model</span><span class="o">.</span><span class="na">predict</span><span class="o">(</span><span class="n">p</span><span class="o">.</span><span class="na">features</span><span class="o">()),</span> <span class="n">p</span><span class="o">.</span><span class="na">label</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">});</span>
<span class="n">Double</span> <span class="n">testMSE</span> <span class="o">=</span>
<span class="n">predictionAndLabel</span><span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="k">new</span> <span class="n">Function</span><span class="o"><</span><span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>,</span> <span class="n">Double</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Double</span> <span class="nf">call</span><span class="o">(</span><span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="n">pl</span><span class="o">)</span> <span class="o">{</span>
<span class="n">Double</span> <span class="n">diff</span> <span class="o">=</span> <span class="n">pl</span><span class="o">.</span><span class="na">_1</span><span class="o">()</span> <span class="o">-</span> <span class="n">pl</span><span class="o">.</span><span class="na">_2</span><span class="o">();</span>
<span class="k">return</span> <span class="n">diff</span> <span class="o">*</span> <span class="n">diff</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}).</span><span class="na">reduce</span><span class="o">(</span><span class="k">new</span> <span class="n">Function2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Double</span> <span class="nf">call</span><span class="o">(</span><span class="n">Double</span> <span class="n">a</span><span class="o">,</span> <span class="n">Double</span> <span class="n">b</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">})</span> <span class="o">/</span> <span class="n">testData</span><span class="o">.</span><span class="na">count</span><span class="o">();</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Test Mean Squared Error: "</span> <span class="o">+</span> <span class="n">testMSE</span><span class="o">);</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Learned regression forest model:\n"</span> <span class="o">+</span> <span class="n">model</span><span class="o">.</span><span class="na">toDebugString</span><span class="o">());</span>
<span class="c1">// Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="na">save</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="s">"myModelPath"</span><span class="o">);</span>
<span class="n">RandomForestModel</span> <span class="n">sameModel</span> <span class="o">=</span> <span class="n">RandomForestModel</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="s">"myModelPath"</span><span class="o">);</span></code></pre></div>
</div>
<div data-lang="python">
<div class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">pyspark.mllib.tree</span> <span class="kn">import</span> <span class="n">RandomForest</span><span class="p">,</span> <span class="n">RandomForestModel</span>
<span class="kn">from</span> <span class="nn">pyspark.mllib.util</span> <span class="kn">import</span> <span class="n">MLUtils</span>
<span class="c"># Load and parse the data file into an RDD of LabeledPoint.</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">MLUtils</span><span class="o">.</span><span class="n">loadLibSVMFile</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">'data/mllib/sample_libsvm_data.txt'</span><span class="p">)</span>
<span class="c"># Split the data into training and test sets (30% held out for testing)</span>
<span class="p">(</span><span class="n">trainingData</span><span class="p">,</span> <span class="n">testData</span><span class="p">)</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">randomSplit</span><span class="p">([</span><span class="mf">0.7</span><span class="p">,</span> <span class="mf">0.3</span><span class="p">])</span>
<span class="c"># Train a RandomForest model.</span>
<span class="c"># Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="c"># Note: Use larger numTrees in practice.</span>
<span class="c"># Setting featureSubsetStrategy="auto" lets the algorithm choose.</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">RandomForest</span><span class="o">.</span><span class="n">trainRegressor</span><span class="p">(</span><span class="n">trainingData</span><span class="p">,</span> <span class="n">categoricalFeaturesInfo</span><span class="o">=</span><span class="p">{},</span>
<span class="n">numTrees</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">featureSubsetStrategy</span><span class="o">=</span><span class="s">"auto"</span><span class="p">,</span>
<span class="n">impurity</span><span class="o">=</span><span class="s">'variance'</span><span class="p">,</span> <span class="n">maxDepth</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">maxBins</span><span class="o">=</span><span class="mi">32</span><span class="p">)</span>
<span class="c"># Evaluate model on test instances and compute test error</span>
<span class="n">predictions</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">testData</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">features</span><span class="p">))</span>
<span class="n">labelsAndPredictions</span> <span class="o">=</span> <span class="n">testData</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">lp</span><span class="p">:</span> <span class="n">lp</span><span class="o">.</span><span class="n">label</span><span class="p">)</span><span class="o">.</span><span class="n">zip</span><span class="p">(</span><span class="n">predictions</span><span class="p">)</span>
<span class="n">testMSE</span> <span class="o">=</span> <span class="n">labelsAndPredictions</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">p</span><span class="p">):</span> <span class="p">(</span><span class="n">v</span> <span class="o">-</span> <span class="n">p</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="n">v</span> <span class="o">-</span> <span class="n">p</span><span class="p">))</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">testData</span><span class="o">.</span><span class="n">count</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Test Mean Squared Error = '</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">testMSE</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Learned regression forest model:'</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">toDebugString</span><span class="p">())</span>
<span class="c"># Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"myModelPath"</span><span class="p">)</span>
<span class="n">sameModel</span> <span class="o">=</span> <span class="n">RandomForestModel</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"myModelPath"</span><span class="p">)</span></code></pre></div>
</div>
</div>
<h2 id="gradient-boosted-trees-gbts">Gradient-Boosted Trees (GBTs)</h2>
<p><a href="http://en.wikipedia.org/wiki/Gradient_boosting">Gradient-Boosted Trees (GBTs)</a>
are ensembles of <a href="mllib-decision-tree.html">decision trees</a>.
GBTs iteratively train decision trees in order to minimize a loss function.
Like decision trees, GBTs handle categorical features,
extend to the multiclass classification setting, do not require
feature scaling, and are able to capture non-linearities and feature interactions.</p>
<p>MLlib supports GBTs for binary classification and for regression,
using both continuous and categorical features.
MLlib implements GBTs using the existing <a href="mllib-decision-tree.html">decision tree</a> implementation. Please see the decision tree guide for more information on trees.</p>
<p><em>Note</em>: GBTs do not yet support multiclass classification. For multiclass problems, please use
<a href="mllib-decision-tree.html">decision trees</a> or <a href="mllib-ensembles.html#Random-Forest">Random Forests</a>.</p>
<h3 id="basic-algorithm-1">Basic algorithm</h3>
<p>Gradient boosting iteratively trains a sequence of decision trees.
On each iteration, the algorithm uses the current ensemble to predict the label of each training instance and then compares the prediction with the true label. The dataset is re-labeled to put more emphasis on training instances with poor predictions. Thus, in the next iteration, the decision tree will help correct for previous mistakes.</p>
<p>The specific mechanism for re-labeling instances is defined by a loss function (discussed below). With each iteration, GBTs further reduce this loss function on the training data.</p>
<h4 id="losses">Losses</h4>
<p>The table below lists the losses currently supported by GBTs in MLlib.
Note that each loss is applicable to one of classification or regression, not both.</p>
<p>Notation: $N$ = number of instances. $y_i$ = label of instance $i$. $x_i$ = features of instance $i$. $F(x_i)$ = model’s predicted label for instance $i$.</p>
<table class="table">
<thead>
<tr><th>Loss</th><th>Task</th><th>Formula</th><th>Description</th></tr>
</thead>
<tbody>
<tr>
<td>Log Loss</td>
<td>Classification</td>
<td>$2 \sum_{i=1}^{N} \log(1+\exp(-2 y_i F(x_i)))$</td><td>Twice binomial negative log likelihood.</td>
</tr>
<tr>
<td>Squared Error</td>
<td>Regression</td>
<td>$\sum_{i=1}^{N} (y_i - F(x_i))^2$</td><td>Also called L2 loss. Default loss for regression tasks.</td>
</tr>
<tr>
<td>Absolute Error</td>
<td>Regression</td>
<td>$\sum_{i=1}^{N} |y_i - F(x_i)|$</td><td>Also called L1 loss. Can be more robust to outliers than Squared Error.</td>
</tr>
</tbody>
</table>
<h3 id="usage-tips-1">Usage tips</h3>
<p>We include a few guidelines for using GBTs by discussing the various parameters.
We omit some decision tree parameters since those are covered in the <a href="mllib-decision-tree.html">decision tree guide</a>.</p>
<ul>
<li>
<p><strong><code>loss</code></strong>: See the section above for information on losses and their applicability to tasks (classification vs. regression). Different losses can give significantly different results, depending on the dataset.</p>
</li>
<li>
<p><strong><code>numIterations</code></strong>: This sets the number of trees in the ensemble. Each iteration produces one tree. Increasing this number makes the model more expressive, improving training data accuracy. However, test-time accuracy may suffer if this is too large.</p>
</li>
<li>
<p><strong><code>learningRate</code></strong>: This parameter should not need to be tuned. If the algorithm behavior seems unstable, decreasing this value may improve stability.</p>
</li>
<li>
<p><strong><code>algo</code></strong>: The algorithm or task (classification vs. regression) is set using the tree [Strategy] parameter.</p>
</li>
</ul>
<h4 id="validation-while-training">Validation while training</h4>
<p>Gradient boosting can overfit when trained with more trees. In order to prevent overfitting, it is useful to validate while
training. The method runWithValidation has been provided to make use of this option. It takes a pair of RDD’s as arguments, the
first one being the training dataset and the second being the validation dataset.</p>
<p>The training is stopped when the improvement in the validation error is not more than a certain tolerance
(supplied by the <code>validationTol</code> argument in <code>BoostingStrategy</code>). In practice, the validation error
decreases initially and later increases. There might be cases in which the validation error does not change monotonically,
and the user is advised to set a large enough negative tolerance and examine the validation curve using <code>evaluateEachIteration</code>
(which gives the error or loss per iteration) to tune the number of iterations.</p>
<h3 id="examples-1">Examples</h3>
<h4 id="classification-1">Classification</h4>
<p>The example below demonstrates how to load a
<a href="http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/">LIBSVM data file</a>,
parse it as an RDD of <code>LabeledPoint</code> and then
perform classification using Gradient-Boosted Trees with log loss.
The test error is calculated to measure the algorithm accuracy.</p>
<div class="codetabs">
<div data-lang="scala">
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.GradientBoostedTrees</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.configuration.BoostingStrategy</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.model.GradientBoostedTreesModel</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.util.MLUtils</span>
<span class="c1">// Load and parse the data file.</span>
<span class="k">val</span> <span class="n">data</span> <span class="k">=</span> <span class="nc">MLUtils</span><span class="o">.</span><span class="n">loadLibSVMFile</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="o">)</span>
<span class="c1">// Split the data into training and test sets (30% held out for testing)</span>
<span class="k">val</span> <span class="n">splits</span> <span class="k">=</span> <span class="n">data</span><span class="o">.</span><span class="n">randomSplit</span><span class="o">(</span><span class="nc">Array</span><span class="o">(</span><span class="mf">0.7</span><span class="o">,</span> <span class="mf">0.3</span><span class="o">))</span>
<span class="k">val</span> <span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">testData</span><span class="o">)</span> <span class="k">=</span> <span class="o">(</span><span class="n">splits</span><span class="o">(</span><span class="mi">0</span><span class="o">),</span> <span class="n">splits</span><span class="o">(</span><span class="mi">1</span><span class="o">))</span>
<span class="c1">// Train a GradientBoostedTrees model.</span>
<span class="c1">// The defaultParams for Classification use LogLoss by default.</span>
<span class="k">val</span> <span class="n">boostingStrategy</span> <span class="k">=</span> <span class="nc">BoostingStrategy</span><span class="o">.</span><span class="n">defaultParams</span><span class="o">(</span><span class="s">"Classification"</span><span class="o">)</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="n">numIterations</span> <span class="k">=</span> <span class="mi">3</span> <span class="c1">// Note: Use more iterations in practice.</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="n">treeStrategy</span><span class="o">.</span><span class="n">numClasses</span> <span class="k">=</span> <span class="mi">2</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="n">treeStrategy</span><span class="o">.</span><span class="n">maxDepth</span> <span class="k">=</span> <span class="mi">5</span>
<span class="c1">// Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="n">treeStrategy</span><span class="o">.</span><span class="n">categoricalFeaturesInfo</span> <span class="k">=</span> <span class="nc">Map</span><span class="o">[</span><span class="kt">Int</span>, <span class="kt">Int</span><span class="o">]()</span>
<span class="k">val</span> <span class="n">model</span> <span class="k">=</span> <span class="nc">GradientBoostedTrees</span><span class="o">.</span><span class="n">train</span><span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">boostingStrategy</span><span class="o">)</span>
<span class="c1">// Evaluate model on test instances and compute test error</span>
<span class="k">val</span> <span class="n">labelAndPreds</span> <span class="k">=</span> <span class="n">testData</span><span class="o">.</span><span class="n">map</span> <span class="o">{</span> <span class="n">point</span> <span class="k">=></span>
<span class="k">val</span> <span class="n">prediction</span> <span class="k">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="o">(</span><span class="n">point</span><span class="o">.</span><span class="n">features</span><span class="o">)</span>
<span class="o">(</span><span class="n">point</span><span class="o">.</span><span class="n">label</span><span class="o">,</span> <span class="n">prediction</span><span class="o">)</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">testErr</span> <span class="k">=</span> <span class="n">labelAndPreds</span><span class="o">.</span><span class="n">filter</span><span class="o">(</span><span class="n">r</span> <span class="k">=></span> <span class="n">r</span><span class="o">.</span><span class="n">_1</span> <span class="o">!=</span> <span class="n">r</span><span class="o">.</span><span class="n">_2</span><span class="o">).</span><span class="n">count</span><span class="o">.</span><span class="n">toDouble</span> <span class="o">/</span> <span class="n">testData</span><span class="o">.</span><span class="n">count</span><span class="o">()</span>
<span class="n">println</span><span class="o">(</span><span class="s">"Test Error = "</span> <span class="o">+</span> <span class="n">testErr</span><span class="o">)</span>
<span class="n">println</span><span class="o">(</span><span class="s">"Learned classification GBT model:\n"</span> <span class="o">+</span> <span class="n">model</span><span class="o">.</span><span class="n">toDebugString</span><span class="o">)</span>
<span class="c1">// Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="n">save</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"myModelPath"</span><span class="o">)</span>
<span class="k">val</span> <span class="n">sameModel</span> <span class="k">=</span> <span class="nc">GradientBoostedTreesModel</span><span class="o">.</span><span class="n">load</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"myModelPath"</span><span class="o">)</span></code></pre></div>
</div>
<div data-lang="java">
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">scala.Tuple2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.HashMap</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Map</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.SparkConf</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaPairRDD</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaRDD</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaSparkContext</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.Function</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.PairFunction</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.regression.LabeledPoint</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.GradientBoostedTrees</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.configuration.BoostingStrategy</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.model.GradientBoostedTreesModel</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.util.MLUtils</span><span class="o">;</span>
<span class="n">SparkConf</span> <span class="n">sparkConf</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">SparkConf</span><span class="o">().</span><span class="na">setAppName</span><span class="o">(</span><span class="s">"JavaGradientBoostedTrees"</span><span class="o">);</span>
<span class="n">JavaSparkContext</span> <span class="n">sc</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">JavaSparkContext</span><span class="o">(</span><span class="n">sparkConf</span><span class="o">);</span>
<span class="c1">// Load and parse the data file.</span>
<span class="n">String</span> <span class="n">datapath</span> <span class="o">=</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="o">;</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">data</span> <span class="o">=</span> <span class="n">MLUtils</span><span class="o">.</span><span class="na">loadLibSVMFile</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="n">datapath</span><span class="o">).</span><span class="na">toJavaRDD</span><span class="o">();</span>
<span class="c1">// Split the data into training and test sets (30% held out for testing)</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">>[]</span> <span class="n">splits</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="na">randomSplit</span><span class="o">(</span><span class="k">new</span> <span class="kt">double</span><span class="o">[]{</span><span class="mf">0.7</span><span class="o">,</span> <span class="mf">0.3</span><span class="o">});</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">trainingData</span> <span class="o">=</span> <span class="n">splits</span><span class="o">[</span><span class="mi">0</span><span class="o">];</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">testData</span> <span class="o">=</span> <span class="n">splits</span><span class="o">[</span><span class="mi">1</span><span class="o">];</span>
<span class="c1">// Train a GradientBoostedTrees model.</span>
<span class="c1">// The defaultParams for Classification use LogLoss by default.</span>
<span class="n">BoostingStrategy</span> <span class="n">boostingStrategy</span> <span class="o">=</span> <span class="n">BoostingStrategy</span><span class="o">.</span><span class="na">defaultParams</span><span class="o">(</span><span class="s">"Classification"</span><span class="o">);</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="na">setNumIterations</span><span class="o">(</span><span class="mi">3</span><span class="o">);</span> <span class="c1">// Note: Use more iterations in practice.</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="na">getTreeStrategy</span><span class="o">().</span><span class="na">setNumClassesForClassification</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="na">getTreeStrategy</span><span class="o">().</span><span class="na">setMaxDepth</span><span class="o">(</span><span class="mi">5</span><span class="o">);</span>
<span class="c1">// Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="n">Map</span><span class="o"><</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">></span> <span class="n">categoricalFeaturesInfo</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o"><</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">>();</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="na">treeStrategy</span><span class="o">().</span><span class="na">setCategoricalFeaturesInfo</span><span class="o">(</span><span class="n">categoricalFeaturesInfo</span><span class="o">);</span>
<span class="kd">final</span> <span class="n">GradientBoostedTreesModel</span> <span class="n">model</span> <span class="o">=</span>
<span class="n">GradientBoostedTrees</span><span class="o">.</span><span class="na">train</span><span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">boostingStrategy</span><span class="o">);</span>
<span class="c1">// Evaluate model on test instances and compute test error</span>
<span class="n">JavaPairRDD</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="n">predictionAndLabel</span> <span class="o">=</span>
<span class="n">testData</span><span class="o">.</span><span class="na">mapToPair</span><span class="o">(</span><span class="k">new</span> <span class="n">PairFunction</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">,</span> <span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="nf">call</span><span class="o">(</span><span class="n">LabeledPoint</span> <span class="n">p</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>(</span><span class="n">model</span><span class="o">.</span><span class="na">predict</span><span class="o">(</span><span class="n">p</span><span class="o">.</span><span class="na">features</span><span class="o">()),</span> <span class="n">p</span><span class="o">.</span><span class="na">label</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">});</span>
<span class="n">Double</span> <span class="n">testErr</span> <span class="o">=</span>
<span class="mf">1.0</span> <span class="o">*</span> <span class="n">predictionAndLabel</span><span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="k">new</span> <span class="n">Function</span><span class="o"><</span><span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>,</span> <span class="n">Boolean</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Boolean</span> <span class="nf">call</span><span class="o">(</span><span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="n">pl</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="o">!</span><span class="n">pl</span><span class="o">.</span><span class="na">_1</span><span class="o">().</span><span class="na">equals</span><span class="o">(</span><span class="n">pl</span><span class="o">.</span><span class="na">_2</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}).</span><span class="na">count</span><span class="o">()</span> <span class="o">/</span> <span class="n">testData</span><span class="o">.</span><span class="na">count</span><span class="o">();</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Test Error: "</span> <span class="o">+</span> <span class="n">testErr</span><span class="o">);</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Learned classification GBT model:\n"</span> <span class="o">+</span> <span class="n">model</span><span class="o">.</span><span class="na">toDebugString</span><span class="o">());</span>
<span class="c1">// Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="na">save</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="s">"myModelPath"</span><span class="o">);</span>
<span class="n">GradientBoostedTreesModel</span> <span class="n">sameModel</span> <span class="o">=</span> <span class="n">GradientBoostedTreesModel</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="s">"myModelPath"</span><span class="o">);</span></code></pre></div>
</div>
<div data-lang="python">
<div class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">pyspark.mllib.tree</span> <span class="kn">import</span> <span class="n">GradientBoostedTrees</span><span class="p">,</span> <span class="n">GradientBoostedTreesModel</span>
<span class="kn">from</span> <span class="nn">pyspark.mllib.util</span> <span class="kn">import</span> <span class="n">MLUtils</span>
<span class="c"># Load and parse the data file.</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">MLUtils</span><span class="o">.</span><span class="n">loadLibSVMFile</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="p">)</span>
<span class="c"># Split the data into training and test sets (30% held out for testing)</span>
<span class="p">(</span><span class="n">trainingData</span><span class="p">,</span> <span class="n">testData</span><span class="p">)</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">randomSplit</span><span class="p">([</span><span class="mf">0.7</span><span class="p">,</span> <span class="mf">0.3</span><span class="p">])</span>
<span class="c"># Train a GradientBoostedTrees model.</span>
<span class="c"># Notes: (a) Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="c"># (b) Use more iterations in practice.</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">GradientBoostedTrees</span><span class="o">.</span><span class="n">trainClassifier</span><span class="p">(</span><span class="n">trainingData</span><span class="p">,</span>
<span class="n">categoricalFeaturesInfo</span><span class="o">=</span><span class="p">{},</span> <span class="n">numIterations</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="c"># Evaluate model on test instances and compute test error</span>
<span class="n">predictions</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">testData</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">features</span><span class="p">))</span>
<span class="n">labelsAndPredictions</span> <span class="o">=</span> <span class="n">testData</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">lp</span><span class="p">:</span> <span class="n">lp</span><span class="o">.</span><span class="n">label</span><span class="p">)</span><span class="o">.</span><span class="n">zip</span><span class="p">(</span><span class="n">predictions</span><span class="p">)</span>
<span class="n">testErr</span> <span class="o">=</span> <span class="n">labelsAndPredictions</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">p</span><span class="p">):</span> <span class="n">v</span> <span class="o">!=</span> <span class="n">p</span><span class="p">)</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">testData</span><span class="o">.</span><span class="n">count</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Test Error = '</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">testErr</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Learned classification GBT model:'</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">toDebugString</span><span class="p">())</span>
<span class="c"># Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"myModelPath"</span><span class="p">)</span>
<span class="n">sameModel</span> <span class="o">=</span> <span class="n">GradientBoostedTreesModel</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"myModelPath"</span><span class="p">)</span></code></pre></div>
</div>
</div>
<h4 id="regression-1">Regression</h4>
<p>The example below demonstrates how to load a
<a href="http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/">LIBSVM data file</a>,
parse it as an RDD of <code>LabeledPoint</code> and then
perform regression using Gradient-Boosted Trees with Squared Error as the loss.
The Mean Squared Error (MSE) is computed at the end to evaluate
<a href="http://en.wikipedia.org/wiki/Goodness_of_fit">goodness of fit</a>.</p>
<div class="codetabs">
<div data-lang="scala">
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.GradientBoostedTrees</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.configuration.BoostingStrategy</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.tree.model.GradientBoostedTreesModel</span>
<span class="k">import</span> <span class="nn">org.apache.spark.mllib.util.MLUtils</span>
<span class="c1">// Load and parse the data file.</span>
<span class="k">val</span> <span class="n">data</span> <span class="k">=</span> <span class="nc">MLUtils</span><span class="o">.</span><span class="n">loadLibSVMFile</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="o">)</span>
<span class="c1">// Split the data into training and test sets (30% held out for testing)</span>
<span class="k">val</span> <span class="n">splits</span> <span class="k">=</span> <span class="n">data</span><span class="o">.</span><span class="n">randomSplit</span><span class="o">(</span><span class="nc">Array</span><span class="o">(</span><span class="mf">0.7</span><span class="o">,</span> <span class="mf">0.3</span><span class="o">))</span>
<span class="k">val</span> <span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">testData</span><span class="o">)</span> <span class="k">=</span> <span class="o">(</span><span class="n">splits</span><span class="o">(</span><span class="mi">0</span><span class="o">),</span> <span class="n">splits</span><span class="o">(</span><span class="mi">1</span><span class="o">))</span>
<span class="c1">// Train a GradientBoostedTrees model.</span>
<span class="c1">// The defaultParams for Regression use SquaredError by default.</span>
<span class="k">val</span> <span class="n">boostingStrategy</span> <span class="k">=</span> <span class="nc">BoostingStrategy</span><span class="o">.</span><span class="n">defaultParams</span><span class="o">(</span><span class="s">"Regression"</span><span class="o">)</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="n">numIterations</span> <span class="k">=</span> <span class="mi">3</span> <span class="c1">// Note: Use more iterations in practice.</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="n">treeStrategy</span><span class="o">.</span><span class="n">maxDepth</span> <span class="k">=</span> <span class="mi">5</span>
<span class="c1">// Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="n">treeStrategy</span><span class="o">.</span><span class="n">categoricalFeaturesInfo</span> <span class="k">=</span> <span class="nc">Map</span><span class="o">[</span><span class="kt">Int</span>, <span class="kt">Int</span><span class="o">]()</span>
<span class="k">val</span> <span class="n">model</span> <span class="k">=</span> <span class="nc">GradientBoostedTrees</span><span class="o">.</span><span class="n">train</span><span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">boostingStrategy</span><span class="o">)</span>
<span class="c1">// Evaluate model on test instances and compute test error</span>
<span class="k">val</span> <span class="n">labelsAndPredictions</span> <span class="k">=</span> <span class="n">testData</span><span class="o">.</span><span class="n">map</span> <span class="o">{</span> <span class="n">point</span> <span class="k">=></span>
<span class="k">val</span> <span class="n">prediction</span> <span class="k">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="o">(</span><span class="n">point</span><span class="o">.</span><span class="n">features</span><span class="o">)</span>
<span class="o">(</span><span class="n">point</span><span class="o">.</span><span class="n">label</span><span class="o">,</span> <span class="n">prediction</span><span class="o">)</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">testMSE</span> <span class="k">=</span> <span class="n">labelsAndPredictions</span><span class="o">.</span><span class="n">map</span><span class="o">{</span> <span class="k">case</span><span class="o">(</span><span class="n">v</span><span class="o">,</span> <span class="n">p</span><span class="o">)</span> <span class="k">=></span> <span class="n">math</span><span class="o">.</span><span class="n">pow</span><span class="o">((</span><span class="n">v</span> <span class="o">-</span> <span class="n">p</span><span class="o">),</span> <span class="mi">2</span><span class="o">)}.</span><span class="n">mean</span><span class="o">()</span>
<span class="n">println</span><span class="o">(</span><span class="s">"Test Mean Squared Error = "</span> <span class="o">+</span> <span class="n">testMSE</span><span class="o">)</span>
<span class="n">println</span><span class="o">(</span><span class="s">"Learned regression GBT model:\n"</span> <span class="o">+</span> <span class="n">model</span><span class="o">.</span><span class="n">toDebugString</span><span class="o">)</span>
<span class="c1">// Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="n">save</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"myModelPath"</span><span class="o">)</span>
<span class="k">val</span> <span class="n">sameModel</span> <span class="k">=</span> <span class="nc">GradientBoostedTreesModel</span><span class="o">.</span><span class="n">load</span><span class="o">(</span><span class="n">sc</span><span class="o">,</span> <span class="s">"myModelPath"</span><span class="o">)</span></code></pre></div>
</div>
<div data-lang="java">
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">scala.Tuple2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.HashMap</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Map</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.SparkConf</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.Function2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaPairRDD</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaRDD</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.JavaSparkContext</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.Function</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.api.java.function.PairFunction</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.regression.LabeledPoint</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.GradientBoostedTrees</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.configuration.BoostingStrategy</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.tree.model.GradientBoostedTreesModel</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.apache.spark.mllib.util.MLUtils</span><span class="o">;</span>
<span class="n">SparkConf</span> <span class="n">sparkConf</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">SparkConf</span><span class="o">().</span><span class="na">setAppName</span><span class="o">(</span><span class="s">"JavaGradientBoostedTrees"</span><span class="o">);</span>
<span class="n">JavaSparkContext</span> <span class="n">sc</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">JavaSparkContext</span><span class="o">(</span><span class="n">sparkConf</span><span class="o">);</span>
<span class="c1">// Load and parse the data file.</span>
<span class="n">String</span> <span class="n">datapath</span> <span class="o">=</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="o">;</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">data</span> <span class="o">=</span> <span class="n">MLUtils</span><span class="o">.</span><span class="na">loadLibSVMFile</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="n">datapath</span><span class="o">).</span><span class="na">toJavaRDD</span><span class="o">();</span>
<span class="c1">// Split the data into training and test sets (30% held out for testing)</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">>[]</span> <span class="n">splits</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="na">randomSplit</span><span class="o">(</span><span class="k">new</span> <span class="kt">double</span><span class="o">[]{</span><span class="mf">0.7</span><span class="o">,</span> <span class="mf">0.3</span><span class="o">});</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">trainingData</span> <span class="o">=</span> <span class="n">splits</span><span class="o">[</span><span class="mi">0</span><span class="o">];</span>
<span class="n">JavaRDD</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">></span> <span class="n">testData</span> <span class="o">=</span> <span class="n">splits</span><span class="o">[</span><span class="mi">1</span><span class="o">];</span>
<span class="c1">// Train a GradientBoostedTrees model.</span>
<span class="c1">// The defaultParams for Regression use SquaredError by default.</span>
<span class="n">BoostingStrategy</span> <span class="n">boostingStrategy</span> <span class="o">=</span> <span class="n">BoostingStrategy</span><span class="o">.</span><span class="na">defaultParams</span><span class="o">(</span><span class="s">"Regression"</span><span class="o">);</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="na">setNumIterations</span><span class="o">(</span><span class="mi">3</span><span class="o">);</span> <span class="c1">// Note: Use more iterations in practice.</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="na">getTreeStrategy</span><span class="o">().</span><span class="na">setMaxDepth</span><span class="o">(</span><span class="mi">5</span><span class="o">);</span>
<span class="c1">// Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="n">Map</span><span class="o"><</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">></span> <span class="n">categoricalFeaturesInfo</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o"><</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">>();</span>
<span class="n">boostingStrategy</span><span class="o">.</span><span class="na">treeStrategy</span><span class="o">().</span><span class="na">setCategoricalFeaturesInfo</span><span class="o">(</span><span class="n">categoricalFeaturesInfo</span><span class="o">);</span>
<span class="kd">final</span> <span class="n">GradientBoostedTreesModel</span> <span class="n">model</span> <span class="o">=</span>
<span class="n">GradientBoostedTrees</span><span class="o">.</span><span class="na">train</span><span class="o">(</span><span class="n">trainingData</span><span class="o">,</span> <span class="n">boostingStrategy</span><span class="o">);</span>
<span class="c1">// Evaluate model on test instances and compute test error</span>
<span class="n">JavaPairRDD</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="n">predictionAndLabel</span> <span class="o">=</span>
<span class="n">testData</span><span class="o">.</span><span class="na">mapToPair</span><span class="o">(</span><span class="k">new</span> <span class="n">PairFunction</span><span class="o"><</span><span class="n">LabeledPoint</span><span class="o">,</span> <span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="nf">call</span><span class="o">(</span><span class="n">LabeledPoint</span> <span class="n">p</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>(</span><span class="n">model</span><span class="o">.</span><span class="na">predict</span><span class="o">(</span><span class="n">p</span><span class="o">.</span><span class="na">features</span><span class="o">()),</span> <span class="n">p</span><span class="o">.</span><span class="na">label</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">});</span>
<span class="n">Double</span> <span class="n">testMSE</span> <span class="o">=</span>
<span class="n">predictionAndLabel</span><span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="k">new</span> <span class="n">Function</span><span class="o"><</span><span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>,</span> <span class="n">Double</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Double</span> <span class="nf">call</span><span class="o">(</span><span class="n">Tuple2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">></span> <span class="n">pl</span><span class="o">)</span> <span class="o">{</span>
<span class="n">Double</span> <span class="n">diff</span> <span class="o">=</span> <span class="n">pl</span><span class="o">.</span><span class="na">_1</span><span class="o">()</span> <span class="o">-</span> <span class="n">pl</span><span class="o">.</span><span class="na">_2</span><span class="o">();</span>
<span class="k">return</span> <span class="n">diff</span> <span class="o">*</span> <span class="n">diff</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}).</span><span class="na">reduce</span><span class="o">(</span><span class="k">new</span> <span class="n">Function2</span><span class="o"><</span><span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">,</span> <span class="n">Double</span><span class="o">>()</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Double</span> <span class="nf">call</span><span class="o">(</span><span class="n">Double</span> <span class="n">a</span><span class="o">,</span> <span class="n">Double</span> <span class="n">b</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">})</span> <span class="o">/</span> <span class="n">data</span><span class="o">.</span><span class="na">count</span><span class="o">();</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Test Mean Squared Error: "</span> <span class="o">+</span> <span class="n">testMSE</span><span class="o">);</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Learned regression GBT model:\n"</span> <span class="o">+</span> <span class="n">model</span><span class="o">.</span><span class="na">toDebugString</span><span class="o">());</span>
<span class="c1">// Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="na">save</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="s">"myModelPath"</span><span class="o">);</span>
<span class="n">GradientBoostedTreesModel</span> <span class="n">sameModel</span> <span class="o">=</span> <span class="n">GradientBoostedTreesModel</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="n">sc</span><span class="o">.</span><span class="na">sc</span><span class="o">(),</span> <span class="s">"myModelPath"</span><span class="o">);</span></code></pre></div>
</div>
<div data-lang="python">
<div class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">pyspark.mllib.tree</span> <span class="kn">import</span> <span class="n">GradientBoostedTrees</span><span class="p">,</span> <span class="n">GradientBoostedTreesModel</span>
<span class="kn">from</span> <span class="nn">pyspark.mllib.util</span> <span class="kn">import</span> <span class="n">MLUtils</span>
<span class="c"># Load and parse the data file.</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">MLUtils</span><span class="o">.</span><span class="n">loadLibSVMFile</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"data/mllib/sample_libsvm_data.txt"</span><span class="p">)</span>
<span class="c"># Split the data into training and test sets (30% held out for testing)</span>
<span class="p">(</span><span class="n">trainingData</span><span class="p">,</span> <span class="n">testData</span><span class="p">)</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">randomSplit</span><span class="p">([</span><span class="mf">0.7</span><span class="p">,</span> <span class="mf">0.3</span><span class="p">])</span>
<span class="c"># Train a GradientBoostedTrees model.</span>
<span class="c"># Notes: (a) Empty categoricalFeaturesInfo indicates all features are continuous.</span>
<span class="c"># (b) Use more iterations in practice.</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">GradientBoostedTrees</span><span class="o">.</span><span class="n">trainRegressor</span><span class="p">(</span><span class="n">trainingData</span><span class="p">,</span>
<span class="n">categoricalFeaturesInfo</span><span class="o">=</span><span class="p">{},</span> <span class="n">numIterations</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="c"># Evaluate model on test instances and compute test error</span>
<span class="n">predictions</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">testData</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">features</span><span class="p">))</span>
<span class="n">labelsAndPredictions</span> <span class="o">=</span> <span class="n">testData</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">lp</span><span class="p">:</span> <span class="n">lp</span><span class="o">.</span><span class="n">label</span><span class="p">)</span><span class="o">.</span><span class="n">zip</span><span class="p">(</span><span class="n">predictions</span><span class="p">)</span>
<span class="n">testMSE</span> <span class="o">=</span> <span class="n">labelsAndPredictions</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">p</span><span class="p">):</span> <span class="p">(</span><span class="n">v</span> <span class="o">-</span> <span class="n">p</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="n">v</span> <span class="o">-</span> <span class="n">p</span><span class="p">))</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">testData</span><span class="o">.</span><span class="n">count</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Test Mean Squared Error = '</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">testMSE</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Learned regression GBT model:'</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">toDebugString</span><span class="p">())</span>
<span class="c"># Save and load model</span>
<span class="n">model</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"myModelPath"</span><span class="p">)</span>
<span class="n">sameModel</span> <span class="o">=</span> <span class="n">GradientBoostedTreesModel</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="s">"myModelPath"</span><span class="p">)</span></code></pre></div>
</div>
</div>
</div> <!-- /container -->
<script src="js/vendor/jquery-1.8.0.min.js"></script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/vendor/anchor.min.js"></script>
<script src="js/main.js"></script>
<!-- MathJax Section -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: { equationNumbers: { autoNumber: "AMS" } }
});
</script>
<script>
// Note that we load MathJax this way to work with local file (file://), HTTP and HTTPS.
// We could use "//cdn.mathjax...", but that won't support "file://".
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function(){
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ["$", "$"], ["\\\\(","\\\\)"] ],
displayMath: [ ["$$","$$"], ["\\[", "\\]"] ],
processEscapes: true,
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
}
});
};
script.src = ('https:' == document.location.protocol ? 'https://' : 'http://') +
'cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
</script>
</body>
</html>