1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
|
<!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.5.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.5.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.5.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.GradientBoostedTrees"><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>
|