Repository navigation
Expand file tree
/
Copy pathDecisionTreesandEnsembleMethods.m
More file actions
1667 lines (1448 loc) · 241 KB
/
Copy pathDecisionTreesandEnsembleMethods.m
File metadata and controls
1667 lines (1448 loc) · 241 KB
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
%[text] %[text:anchor:T_BB73E10C] # Decision Trees and Ensemble Methods
%[text] [⇦ Main Menu](file:../MainMenu.m)
%[text] This script supports the train-and-evaluate part of the machine learning workflow. After building candidate features and controlling complexity, the next question is whether a tree-based model can capture patterns that a single global equation still misses.
%[text]{"align":"center"} 
%[text:tableOfContents]{"heading":"Table of Contents"} %[text:anchor:M_597CA885]
%[text] %[text:anchor:H_51183E7B] **Before you get started:**
%[text] %[text:anchor:H_BF646A47] This live script is intended to be used with the code hidden. On the MATLAB toolstrip, select **View** \> **Hide Code**. Alternatively, select **Hide Code** using the icon  at the top right of the Live Editor pane.
%[text]  Although the code is hidden, some interactivity requires familiarity with MATLAB. If you need more instruction, consider taking [MATLAB Onramp](https://matlabacademy.mathworks.com/details/matlab-onramp/gettingstarted), a free 2-hour online tutorial that teaches the essentials of MATLAB.
%[text] %[text:anchor:H_8F8A032D]  For an optimal experience, follow the instructions and steps in the given sequence. Proceed to a new section only after completing the preceding one. Some sections depend on variables created in prior sections and will generate errors if run out of order.
%[text] The  and  icons mark two different kinds of interactive activities in this script. The  usually marks an exploration activity that helps you visualize a concept introduced in the lesson. The  marks an activity that checks your understanding and may be used for grading or completion checks by your instructor.
%%
%[text] ## Why Tree-Based Models?
%[text] A simple linear model is still a useful baseline, but local rules or combinations of local rules better describe many regression problems. Regression trees divide the predictor space into regions using a sequence of decision rules. For example, a tree might first split on temperature and then, within one temperature range, split again on humidity. Because later decisions depend on earlier ones, trees naturally capture nonlinear behavior and interactions between predictors. However, regression trees are prone to overfitting, leading to models that can be highly sensitive to the training data and may generalize poorly to new observations. Ensemble methods address this limitation by combining predictions from many trees, reducing variability, improving robustness, and often achieving better predictive performance than a single tree. A single tree is useful when interpretability is important, while an ensemble is often preferred when prediction accuracy and stability are the primary goals.
%[text] Then your three questions become:
%[text] 1. How does a regression tree make predictions by following a sequence of decision rules?
%[text] 2. How can those decision rules capture nonlinear patterns and predictor interactions?
%[text] 3. When is an ensemble of trees preferable to a single regression tree? \
%[text] In this lesson, the main comparison is between a simple baseline and two tree-based approaches. We will focus on three questions:
%[text] - What kind of pattern can a single tree represent?
%[text] - How does an ensemble improve on one tree?
%[text] - When is the extra flexibility worth it? \
%[text:table]
%[text] | **Model** | **Key Idea** | **Strength** |
%[text] | --- | --- | --- |
%[text] | Linear Baseline | Fit one global relationship | Simple, interpretable reference model |
%[text] | Regression Tree | Split data into regions using decision rules | Captures thresholds and local behavior |
%[text] | Ensemble of Trees | Combine predictions from many trees | Often improves accuracy and robustness |
%[text:table]
%%
%[text] ### A Quick Baseline Reminder
%[text] A single global model is still a helpful reference because it tells us what a simple approach can and cannot explain. The [Feature Engineering and Regularization](file:FeatureEngRegularization.m) lesson handles linear-model refinement in detail, so here we will treat the linear model only as a baseline for comparison.
%[text] In this lesson, the focus is different: when patterns are segmented, thresholded, or strongly nonlinear, tree-based models often become the better next step.
%[text] The comparison below highlights two different modeling decisions. In the **Feature Engineering Keeps a Global Fit** example, adding an appropriate feature allows a single regression model to capture the pattern in the data with low error. In the **Threshold Pattern Suggests a Tree** example, the data follow rule-based, threshold-like behavior that is difficult for a single regression model to represent, making a decision tree a more natural choice. Together, these examples show that improving a model may involve either engineering better features or selecting a different model family.
%[text]  **Try**. Click **Display Baseline Comparison**.
DefaultStyle = InitializeDefaultStyle();
%[control:button:5fe9]{"position":[1,2]}
BaselineExample = MakeBaselineReminderExample();
tiledlayout(1,2,Padding="compact",TileSpacing="compact")
axFeature = nexttile;
FeatureScatter = scatter(axFeature,BaselineExample.FeatureCase.X,BaselineExample.FeatureCase.Y,DefaultStyle.DataMarkerSize,"filled",MarkerFaceAlpha=DefaultStyle.DataMarkerFaceAlpha,SeriesIndex=DefaultStyle.DataSeriesIndex);
hold(axFeature,"on")
FeatureFit = plot(axFeature,BaselineExample.FeatureCase.XGrid,BaselineExample.FeatureCase.YGrid,LineWidth=DefaultStyle.PrimaryLineWidth,SeriesIndex=DefaultStyle.EngineeredFeatureSeriesIndex);
hold(axFeature,"off")
xlabel(axFeature,"$x$",Interpreter=DefaultStyle.Interpreter)
ylabel(axFeature,"$y$",Interpreter=DefaultStyle.Interpreter)
title(axFeature,"Feature Engineering Keeps a Global Fit",Interpreter=DefaultStyle.Interpreter)
legend(axFeature,[FeatureScatter FeatureFit],["Data","Quadratic-feature fit"],Location="best")
ApplyDefaultAxesStyle(axFeature,DefaultStyle)
text(axFeature,0.03,0.95,"MSE = " + compose("%.2f",BaselineExample.FeatureCase.MSE),Units="normalized",VerticalAlignment="top",BackgroundColor=GetAxesBackgroundColor(axFeature),Margin=DefaultStyle.AnnotationMargin,Interpreter=DefaultStyle.Interpreter)
axThreshold = nexttile;
ThresholdScatter = scatter(axThreshold,BaselineExample.TreeCase.X,BaselineExample.TreeCase.Y,DefaultStyle.DataMarkerSize,"filled",MarkerFaceAlpha=DefaultStyle.DataMarkerFaceAlpha,SeriesIndex=DefaultStyle.DataSeriesIndex);
hold(axThreshold,"on")
ThresholdBaseline = plot(axThreshold,BaselineExample.TreeCase.XGrid,BaselineExample.TreeCase.LinearFit,"--",LineWidth=DefaultStyle.SecondaryLineWidth,SeriesIndex=DefaultStyle.LinearBaselineSeriesIndex);
ThresholdTree = plot(axThreshold,BaselineExample.TreeCase.XGrid,BaselineExample.TreeCase.TreeFit,LineWidth=DefaultStyle.PrimaryLineWidth,SeriesIndex=DefaultStyle.TreeSeriesIndex);
hold(axThreshold,"off")
xlabel(axThreshold,"$x$",Interpreter=DefaultStyle.Interpreter)
ylabel(axThreshold,"$y$",Interpreter=DefaultStyle.Interpreter)
title(axThreshold,"Threshold Pattern Suggests a Tree",Interpreter=DefaultStyle.Interpreter)
legend(axThreshold,[ThresholdScatter ThresholdBaseline ThresholdTree],["Data","Linear baseline","Tree fit"],Location="best")
ApplyDefaultAxesStyle(axThreshold,DefaultStyle)
text(axThreshold,0.03,0.95,["Linear MSE = " + compose("%.2f",BaselineExample.TreeCase.LinearMSE),"Tree MSE = " + compose("%.2f",BaselineExample.TreeCase.TreeMSE)],Units="normalized",VerticalAlignment="top",BackgroundColor=GetAxesBackgroundColor(axThreshold),Margin=DefaultStyle.AnnotationMargin,Interpreter=DefaultStyle.Interpreter)
sgtitle("Quick Baseline Reminder",Interpreter=DefaultStyle.Interpreter)
%%
%[text] ### Regression Trees
%[text] Regression trees are a **supervised learning** method that predicts outcomes by splitting data into smaller groups using simple if–else rules. Unlike linear regression, which fits one global equation, a tree makes local predictions after following a path from the root to a leaf.
%[text] The **root node** represents the first and often most important split in the data. Internal nodes apply additional decision rules that divide the predictor space into smaller regions. Each branch corresponds to the outcome of a split, directing observations left or right through the tree. The **leaf nodes** are the terminal regions of the model and contain the final prediction. A prediction is made by starting at the root node and following the appropriate branches until reaching a leaf node. This sequence of decisions allows a regression tree to make different predictions for different regions of the predictor space rather than using a single global model.
%[text]  **Try**. Click **Display Parts of a Decision Tree**.
DefaultStyle = InitializeDefaultStyle();
ShowStaticTreeDiagram(MakeTreeTerminologySpec(),DefaultStyle,FigureName="Decision Tree Anatomy",FigureSize=[820 360]);
%[control:button:439a]{"position":[1,2]}
%%
%[text] ### Explore Decision Paths
%[text] Here, you will step through a prediction one decision at a time. Starting at the root, the model evaluates conditions such as `Hour < 12` and follows a path based on your input values. The visualization highlights each branch until the final prediction is reached. As you explore, focus on how the model evaluates decisions in sequence. Notice that only some predictors are used along a given path. Compare how different inputs lead to different predictions.
%[text] For example, if `Hour = 15` and `Temperature = 72`, the model first checks `Hour < 12`. That condition is false, so it moves to the right branch and then checks `Temperature < 80`. That condition is true, so the model predicts `5100 MW`.
%[text]  **Try**. Drag the **Hour** and **Temperature** sliders to follow the decision path and view the final prediction. The figure footer and the text output below report the same path in words.
DefaultStyle = InitializeDefaultStyle();
InteractiveTreeSpec = MakeInteractiveTreeSpec();
Hour = 0; %[control:slider:88d8]{"position":[8,9]}
Temperature = 0; %[control:slider:8da7]{"position":[15,16]}
InteractiveTree = EvaluateInteractiveTree(InteractiveTreeSpec,Hour,Temperature);
RenderInteractiveTreeDemo(InteractiveTreeSpec,InteractiveTree,DefaultStyle)
disp(FormatTreeDecisionTrace(InteractiveTreeSpec,InteractiveTree))
disp("Predicted Load = " + compose("%.0f",InteractiveTree.Prediction) + " MW")
%[text] %[text:anchor:TMP_0026]  **Reflect**. How many leaf nodes does the tree contain? What variable is used for splitting? What values appear at the leaf nodes? How does this differ from the coefficient-based representation of linear regression?
%%
%[text]  **Exercise 1.** For the decision tree shown in the figure and described below, if `Hour = 9` and `Temp = 63 deg F`, what will the load be?
%[text]
%[text]{"align":"center"} 
CheckAnswer("Exercise1","Select") %[control:dropdown:4e16]{"position":[25,33]}
%%
%[text] #### Connecting Tree Structure to Model Predictions
%[text] Regression trees can be viewed both as a collection of decision rules and as a fitted function. Showing these perspectives side by side helps connect each split to both a branching rule in the tree and a change in the model’s predictions. As additional splits are added, the tree grows more complex, and the fitted curve becomes more detailed. This makes it easier to see how decision boundaries create distinct prediction regions.
%[text]  **Try**. Drag the **Number of Splits** slider to change the number of splits and observe how the fitted curve changes. As the tree grows, it can fit the training data more closely, but too many splits can overfit and may require pruning or validation-based model selection.
DefaultStyle = InitializeDefaultStyle();
[x,y] = GetLoadMayDayData();
N =1; %[control:slider:49a5]{"position":[4,5]}
mdl = ShowRegressionTreeSideBySide(x,y,N,DefaultStyle);
%%
%[text] ### **Ensemble of Trees**
%[text] Decision trees partition the predictor space into regions and fit a simple prediction within each region. They are easy to interpret but can be sensitive to noise and small changes in the data. Ensemble methods improve performance by combining many trees into a single model. A single shallow tree, often called a weak learner, captures only simple patterns, but many trees working together can form a stronger predictor. Two common ensemble approaches are **bagging** and **boosting**.
%[text] - **Bagging (bootstrap aggregation)** trains trees independently on different random subsets of the data and averages their predictions, reducing variance and improving stability.
%[text] - **Boosting** trains trees sequentially, with each new tree focusing on correcting errors made by the current ensemble, reducing bias and improving accuracy. \
%[text] The animation below still emphasizes boosting so you can watch later trees correct earlier errors in sequence, but the comparison now includes bagging on the same data. This makes it easier to see the difference between averaging many independently fit trees and sequentially correcting residual error. While training error typically decreases as more trees are added, generalization should be evaluated using validation or holdout data rather than training error alone.
%[text] In the top plot, the filled circles are the observed training data. The dashed line is the prediction from a single regression tree, used as a baseline. The bagging and boosting curves show how the ensemble prediction changes as more trees are added.
%[text] In summary, **bagging gain** and **boosting gain** mean the percent reduction in training MSE relative to that single-tree baseline. A positive value means the ensemble fits the training data better than one tree; a negative value means it did worse on training MSE for that setting.
%[text] `NumTrees` is the number of trees included in the ensemble, while `MaxSplits` is the number of decision splits each individual tree is allowed to make, so it controls the complexity of each tree rather than the number of trees.
%[text]  **Try**. Click **Fit Ensemble of Trees** to view an example that models the hourly electricity load in a single day.
%[text] 1. Drag the **`NumTrees`** slider to increase the number of trees in the ensemble, then click **Fit Ensemble of Trees** to rerun this section.
%[text] 2. Drag the **`NumSplits`** slider to increase tree depth, then click **Fit Ensemble of Trees** to rerun this section.
%[text] 3. Compare the bagging and boosting curves, then note which one reduces training error more quickly and which one looks more stable. \
DefaultStyle = InitializeDefaultStyle();
[x,y] = GetLoadMayDayData();
NumTrees = 1; %[control:slider:2ed9]{"position":[12,13]}
NumSplits = 1; %[control:slider:8be8]{"position":[13,14]}
%[control:button:961b]{"position":[1,2]}
if ~isfinite(NumTrees)
NumTrees = 2;
end
if ~isfinite(NumSplits)
NumSplits = 2;
end
NumTrees = max(1,round(NumTrees));
NumSplits = max(1,round(NumSplits));
ens = ShowEnsembleTreeDemo(x,y,NumTrees,NumSplits,DefaultStyle);
%[text]  **Reflect**. How many trees do you think we need before the fit stabilizes? Will adding trees make the prediction more or less flexible? Why might the ensemble outperform a single tree?
%%
%[text] ### Connection to Feature Engineering and Regularization
%[text] If our main problem is too many predictors rather than the wrong model family, return to the [Feature Engineering and Regularization](file:FeatureEngRegularization.m) lesson, which focuses on stepwise regression, Lasso, and other ways to keep a linear model smaller and easier to generalize.
%[text] In this lesson, we stay with a different question: when a linear baseline is still too rigid, does a single tree help, or do we need an ensemble of trees?
%%
%[text] ### Choosing Between a Baseline, a Tree, and an Ensemble
%[text] After learning how regression trees make predictions, the next step is deciding which model is most appropriate for a particular problem. In practice, model selection is part of the **train-and-evaluate** stage of the machine learning workflow. Rather than trying every possible model, you can often begin by looking at the overall structure of the data.
%[text] As you explore the examples below, look for the relationship between the predictors and the response. Ask yourself:
%[text] - Does the data follow a mostly linear trend?
%[text] - Is there a smooth nonlinear pattern that could be captured by a single global model?
%[text] - Do clear thresholds or regions appear where different rules seem to apply?
%[text] - Does the data contain complex patterns or substantial noise? \
%[text] The answers to these questions can help guide your model choice. Linear regression provides a simple, interpretable baseline when a single trend describes the data well. Regression trees are useful when predictions depend on thresholds or local decision rules. Ensembles of trees combine many trees to improve stability and predictive accuracy when patterns become more complex or noisy.
%[text]{"align":"center"} 
%[text] The examples below illustrate common data patterns and the modeling approaches that are often a good starting point for each one. As you compare the plots, focus on what features of the data motivate the choice of model.
%[text:table]
%[text] | **If your data looks like...** | **Try this model** | **Why** |
%[text] | --- | --- | --- |
%[text] | Mostly linear trends | Linear Regression | Useful baseline and easy to interpret |
%[text] | Smooth global nonlinear patterns | Feature engineering or nonlinear regression | Keeps one global model while capturing curvature |
%[text] | Thresholds or segmented regions | Regression Tree | Captures local rules directly |
%[text] | Complex nonlinear patterns with noise | Ensemble of Trees | Improves stability and predictive accuracy |
%[text:table]
%%
%[text]  **Try**. Select a dataset from the **Select a dataset** dropdown menu and predict which model will perform best based on the pattern you observe.
%[text] Dataset summaries: Dataset 1 is mostly linear. Dataset 2 is a smooth nonlinear parabola. Dataset 3 combines periodic structure, trend, and noise. Dataset 4 uses thresholded multivariate interactions. Use these summaries if you cannot inspect the plots visually.
%%\ Create Multiple Example Datasets
DataSetChoice = "Select"; %[control:dropdown:0ca8]{"position":[17,25]}
[T,predictorVars,plotTitle,PatternSummary,isMultivariate] = GetExampleDataset(DataSetChoice);
if isempty(T)
disp("Select a valid option.")
return
end
%%\ Dataset Visualization
DefaultStyle = InitializeDefaultStyle();
if isMultivariate
figure
tiledlayout(1,2,Padding="compact",TileSpacing="compact")
axX1 = nexttile;
scatter(axX1,T.X1,T.Y,DefaultStyle.DataMarkerSize,"filled",MarkerFaceAlpha=DefaultStyle.DataMarkerFaceAlpha,SeriesIndex=DefaultStyle.DataSeriesIndex)
xlabel(axX1,"$X_1$",Interpreter=DefaultStyle.Interpreter)
ylabel(axX1,"$Y$",Interpreter=DefaultStyle.Interpreter)
title(axX1,"Threshold Pattern in $X_1$",Interpreter=DefaultStyle.Interpreter)
ApplyDefaultAxesStyle(axX1,DefaultStyle)
axX2 = nexttile;
scatter(axX2,T.X2,T.Y,DefaultStyle.DataMarkerSize,"filled",MarkerFaceAlpha=DefaultStyle.DataMarkerFaceAlpha,SeriesIndex=DefaultStyle.DataSeriesIndex)
xlabel(axX2,"$X_2$",Interpreter=DefaultStyle.Interpreter)
ylabel(axX2,"$Y$",Interpreter=DefaultStyle.Interpreter)
title(axX2,"Threshold Pattern in $X_2$",Interpreter=DefaultStyle.Interpreter)
ApplyDefaultAxesStyle(axX2,DefaultStyle)
else
figure
scatter(T.X,T.Y,DefaultStyle.DataMarkerSize,"filled",MarkerFaceAlpha=DefaultStyle.DataMarkerFaceAlpha,SeriesIndex=DefaultStyle.DataSeriesIndex,DisplayName=DataSetChoice)
xlabel("$X$",Interpreter=DefaultStyle.Interpreter)
ylabel("$Y$",Interpreter=DefaultStyle.Interpreter)
title(plotTitle,Interpreter=DefaultStyle.Interpreter)
ApplyDefaultAxesStyle(gca,DefaultStyle)
end
disp(PatternSummary)
%%
%[text] ### Compare Model Performance
%[text] Run these models on the dataset you selected in the previous section to evaluate how well each approach captures the underlying patterns. Compare model accuracy using mean squared error (MSE) and examine the prediction plots to see when a single tree is enough and when an ensemble improves on it. Use the MSE table as the primary text summary of model differences, and use the plots as visual confirmation.
%[text]  **Try**. Click **Compare Regression Models** to view an example that models the hourly electricity load in a single day.
%%\ Compare Regression Models %[text:anchor:TMP_5a30]
%[control:button:9485]{"position":[1,2]}
DefaultStyle = InitializeDefaultStyle();
[TTrain,predictorVars,plotTitle,~,isMultivariate] = GetExampleDataset(DataSetChoice);
if isempty(TTrain)
disp("Select a valid dataset option first.")
return
end
% Partition data (30% holdout)
cv = cvpartition(height(TTrain),HoldOut=0.3);
idx = training(cv);
Ttrain = TTrain(idx,:);
Ttest = TTrain(~idx,:);
% Extract predictors and response for training and testing
Xtrain = Ttrain{:,predictorVars};
Ytrain = Ttrain{:,"Y"};
Xtest = Ttest{:,predictorVars};
Ytest = Ttest{:,"Y"};
% Ensure correct shapes: for univariate, use column vectors; for multivariate keep as matrix
if isvector(Xtrain) || size(Xtrain,2)==1
Xtrain = Xtrain(:);
Xtest = Xtest(:);
end
Ytrain = Ytrain(:);
Ytest = Ytest(:);
%%\ 1. Linear Regression
mdlLinear = fitlm(Ttrain(:,[predictorVars,"Y"]),"Y");
%%\ 2. Regression Tree
mdlTree = fitrtree(Xtrain,Ytrain);
%%\ 3. Ensemble Model
mdlEnsemble = fitrensemble(Xtrain,Ytrain);
%%\ Make Predictions
yPredLinear = predict(mdlLinear,Xtest);
yPredTree = predict(mdlTree,Xtest);
yPredEnsemble = predict(mdlEnsemble,Xtest);
%%\ Compute MSE
mse = @(y,yhat) mean((y - yhat).^2);
MSELinear = mse(Ytest,yPredLinear);
MSETree = mse(Ytest,yPredTree);
MSEEnsemble = mse(Ytest,yPredEnsemble);
%%\ Compare Results
ModelNames = ["Linear Baseline"; "Tree"; "Ensemble"];
MSEValues = [MSELinear; MSETree; MSEEnsemble];
ResultsTable = table(ModelNames,MSEValues);
BestModelName = ModelNames(find(MSEValues == min(MSEValues),1,"first"));
disp("Comparison summary: Lower MSE indicates the better fit on this dataset. The lowest MSE here is from " + BestModelName + ".")
%%\ Visualize Model Fits in Dataset Space
figure(Units="normalized",Position=[0.05 0.05 0.9 1.1])
tiledlayout(1,3,Padding="compact",TileSpacing="compact")
models = {mdlLinear,mdlTree,mdlEnsemble};
titles = ["Linear Baseline","Tree","Ensemble"];
if isMultivariate
xPlot = Ttest.X1;
yPlot = Ytest;
xGrid = linspace(min(TTrain.X1),max(TTrain.X1),300)';
x2Reference = median(TTrain.X2);
PredictionTable = table(xGrid,repmat(x2Reference,size(xGrid)),VariableNames={'X1','X2'});
xLabel = "$X_1$";
yLabel = "$Y$";
titleSuffix = " (slice at median $X_2$)";
else
xPlot = Ttest.X;
yPlot = Ytest;
xGrid = linspace(min(TTrain.X),max(TTrain.X),300)';
PredictionTable = table(xGrid,VariableNames={'X'});
xLabel = "$X$";
yLabel = "$Y$";
titleSuffix = ": " + plotTitle;
end
for i = 1:3
axModel = nexttile;
scatter(axModel,xPlot,yPlot,DefaultStyle.DataMarkerSize,"filled",MarkerFaceAlpha=DefaultStyle.DataMarkerFaceAlpha,SeriesIndex=DefaultStyle.DataSeriesIndex)
hold(axModel,"on")
if i == 1
yFit = predict(models{i},PredictionTable);
else
yFit = predict(models{i},PredictionTable{:,predictorVars});
end
plot(axModel,xGrid,yFit,LineWidth=DefaultStyle.PrimaryLineWidth,SeriesIndex=DefaultStyle.TreeSeriesIndex)
xlabel(axModel,xLabel,Interpreter=DefaultStyle.Interpreter)
ylabel(axModel,yLabel,Interpreter=DefaultStyle.Interpreter)
title(axModel,(titles(i) + titleSuffix),Interpreter=DefaultStyle.Interpreter)
ApplyDefaultAxesStyle(axModel,DefaultStyle)
end
figure
hMSE = bar(MSEValues);
hMSE.SeriesIndex = DefaultStyle.ComparisonSeriesIndex;
xticks(1:numel(ModelNames))
xticklabels(ModelNames)
xtickangle(45)
ylabel("MSE",Interpreter=DefaultStyle.Interpreter)
title("Model Comparison",Interpreter=DefaultStyle.Interpreter)
ApplyDefaultAxesStyle(gca,DefaultStyle)
disp(ResultsTable)
%%
%[text]  **Exercise 2.** A dataset shows clear thresholds or segmented regions rather than one smooth global trend. Which model is the best first flexible choice?
CheckAnswer("Exercise2","Select"); %[control:dropdown:830a]{"position":[25,33]}
%%
%[text]  **Exercise 3.** A dataset shows a complex pattern with trends, noise, and nonlinear relationships. Which model is most appropriate?
CheckAnswer("Exercise3","Select"); %[control:dropdown:0db3]{"position":[25,33]}
%%
%[text] ### Summary
%[text] This lesson focused on when tree-based regression models are worth using. We used a simple linear model as a baseline, explored how a regression tree makes local decisions, and then saw how ensembles combine many trees to improve predictive performance. These activities showed how model choice depends on whether the data look mostly global, strongly segmented, or complex and noisy.
%%
%[text] ## Further Exploration
%[text] Review the [Additional Resources](file:../InstructorResources/AdditionalResources.m:M_080d) section to find more materials for further learning.
%%
%[text] [⇦ Return to Main Menu](file:../MainMenu.m)
%%
%[text] ## Help us Improve
%[text] [Share your feedback](<matlab: ShareFeedback>) to help us improve this module.
%%
%[text] %[text:anchor:H_0AAABA39] ## Local Helper Functions
%[text] If you wish to see the details of the code, on the MATLAB toolstrip select **View** \> **Output Inline**. Alternatively, select **Output Inline** using the icon  at the top right of the Live Editor pane.
function Style = InitializeDefaultStyle()
Style = DefaultPlotStyle();
ApplyDefaultStyle(Style);
end
%%
function [T,predictorVars,plotTitle,PatternSummary,isMultivariate] = GetExampleDataset(DataSetChoice)
arguments
DataSetChoice (1,1) string
end
rng default
n = 150;
T = table();
predictorVars = strings(1,0);
plotTitle = "";
PatternSummary = "";
isMultivariate = false;
switch DataSetChoice
case {"Dataset 1","Dataset 1: Mostly Linear"}
X = randn(n,1) * 10;
Y = 3*X + 5 + randn(n,1)*5;
T = table(X,Y);
predictorVars = "X";
plotTitle = "Dataset 1: Mostly Linear";
PatternSummary = "Pattern summary: Dataset 1 follows a mostly linear trend with noise, so a global linear model can be competitive.";
case {"Dataset 2","Dataset 2: Nonlinear"}
X = linspace(-10,10,n)';
Y = X.^2 + randn(n,1)*10;
T = table(X,Y);
predictorVars = "X";
plotTitle = "Dataset 2: Nonlinear";
PatternSummary = "Pattern summary: Dataset 2 is a smooth nonlinear parabola, so feature engineering or another global nonlinear model may work well.";
case {"Dataset 3","Dataset 3: Complex"}
X = linspace(0,24,n)';
Y = 50 + 10*sin(X/24*2*pi) + 0.5*X + randn(n,1)*8;
T = table(X,Y);
predictorVars = "X";
plotTitle = "Dataset 3: Complex";
PatternSummary = "Pattern summary: Dataset 3 mixes periodic structure, trend, and noise, so more flexible models may outperform a simple global line.";
case {"Dataset 4","Dataset 4: Multivariate with Interactions","Dataset 4:Multivariate with Interactions"}
X1 = 10*rand(n,1);
X2 = 10*rand(n,1);
Y = 20 + 6*(X1 > 5) + 8*(X2 > 6) + 0.8*X1.*(X2 > 6) + randn(n,1)*1.8;
T = table(X1,X2,Y);
predictorVars = ["X1","X2"];
plotTitle = "Dataset 4: Multivariate with Interactions";
PatternSummary = "Pattern summary: Dataset 4 uses thresholded multivariate interactions, so tree-based models are a natural candidate.";
isMultivariate = true;
otherwise
return
end
end
%%
function mdl = ShowRegressionTreeSideBySide(x,y,N,Style)
% ShowRegressionTreeSideBySide
% Animate a regression tree fit alongside its tree structure.
arguments
x (:,1) double
y (:,1) double
N (1,1) {mustBeInteger,mustBePositive}
Style (1,1) struct = DefaultPlotStyle()
end
xnew = linspace(min(x),max(x),400)';
fig = figure(Name="Regression Tree: Fit and Structure",NumberTitle="off");
ApplyFullscreenFigure(fig)
t = tiledlayout(fig,1,2,TileSpacing="compact",Padding="compact");
axFit = nexttile(t,1);
dataScatter = scatter(axFit,x,y,Style.DataMarkerSize,"filled",MarkerFaceAlpha=Style.DataMarkerFaceAlpha,SeriesIndex=Style.DataSeriesIndex);
hold(axFit,"on")
fitLine = plot(axFit,xnew,nan(size(xnew)),LineWidth=Style.PrimaryLineWidth,SeriesIndex=Style.TreeSeriesIndex);
splitLegend = plot(axFit,nan,nan,"--",LineWidth=Style.SecondaryLineWidth,SeriesIndex=Style.ReferenceSeriesIndex);
fitLegend = legend(axFit,[dataScatter fitLine splitLegend],["Data","Tree fit","Decision splits"],Location="best");
fitLegend.Interpreter = char(Style.Interpreter);
xlabel(axFit,"x",Interpreter=Style.Interpreter)
ylabel(axFit,"y",Interpreter=Style.Interpreter)
title(axFit,"Regression Tree Fit",Interpreter=char(Style.Interpreter))
ApplyDefaultAxesStyle(axFit,Style)
xlim(axFit,[min(x) max(x)])
axTree = nexttile(t,2);
axis(axTree,"off")
xlim(axTree,[0 1])
ylim(axTree,[0 1])
title(axTree,"Tree Structure",Interpreter=char(Style.Interpreter))
for NumSplits = 1:N
mdl = fitrtree(x,y,MaxNumSplits=NumSplits,MinParentSize=2,Prune="off");
fitLine.YData = predict(mdl,xnew);
if NumSplits > 1
validLines = splitLines(isgraphics(splitLines));
if ~isempty(validLines)
delete(validLines)
end
end
splitPoints = mdl.CutPoint(~isnan(mdl.CutPoint));
splitLines = gobjects(numel(splitPoints),1);
for k = 1:numel(splitPoints)
splitLines(k) = xline(axFit,splitPoints(k),"--",LineWidth=Style.SecondaryLineWidth,SeriesIndex=Style.ReferenceSeriesIndex);
splitLines(k).Annotation.LegendInformation.IconDisplayStyle = "off";
end
RenderRegressionTree(axTree,mdl,Style)
title(axTree,"Tree Structure (" + string(NumSplits) + " split" + pluralS(NumSplits) + ")",Interpreter=char(Style.Interpreter))
drawnow
if NumSplits < N
pause(0.6)
end
end
end
%%
function RenderRegressionTree(Ax,mdl,Style)
arguments
Ax
mdl
Style (1,1) struct = DefaultPlotStyle()
end
Layout = MakeRegressionTreeLayout(mdl);
children = mdl.Children;
branchLabelFontSize = ResolveTreeFontSize( ...
Style.TreeBranchLabelFontSize, ...
max(Layout.NumLeaves - Style.TreeDenseLeafThreshold,0), ...
Style.TreeFontShrinkScale, ...
Style.MinimumTreeBranchFontSize);
nodeFontSize = ResolveTreeFontSize( ...
Style.TreeNodeFontSize, ...
ceil(max(Layout.NumLeaves - Style.TreeDenseNodeThreshold,0) / Style.TreeDenseNodeStep), ...
Style.TreeFontShrinkScale, ...
Style.MinimumTreeNodeFontSize);
cla(Ax)
hold(Ax,"on")
axis(Ax,"off")
xlim(Ax,[0 1])
ylim(Ax,[0 1])
ApplyDefaultAxesStyle(Ax,Style)
for k = 1:Layout.NumNodes
if ~mdl.IsBranchNode(k)
continue
end
parentPos = Layout.Positions(k,:);
leftChild = children(k,1);
rightChild = children(k,2);
if leftChild > 0
leftPos = Layout.Positions(leftChild,:);
plot(Ax,[parentPos(1) leftPos(1)],[parentPos(2)-Layout.NodeHeight/2 leftPos(2)+Layout.NodeHeight/2],LineWidth=Style.TreeDiagramLineWidth,SeriesIndex=Style.TreeBackgroundSeriesIndex)
drawBranchLabel(Ax,0.52*parentPos + 0.48*leftPos + [-0.03 0.03],"yes",Style,FontSize=branchLabelFontSize)
end
if rightChild > 0
rightPos = Layout.Positions(rightChild,:);
plot(Ax,[parentPos(1) rightPos(1)],[parentPos(2)-Layout.NodeHeight/2 rightPos(2)+Layout.NodeHeight/2],LineWidth=Style.TreeDiagramLineWidth,SeriesIndex=Style.TreeBackgroundSeriesIndex)
drawBranchLabel(Ax,0.52*parentPos + 0.48*rightPos + [0.03 0.03],"no",Style,FontSize=branchLabelFontSize)
end
end
for k = 1:Layout.NumNodes
if mdl.IsBranchNode(k)
drawNode(Ax,Layout.Positions(k,:),Layout.Labels(k),Style,Width=Layout.NodeWidth,Height=Layout.NodeHeight,EdgeColor=GetSeriesColor(Ax,Style.TreeBranchNodeSeriesIndex),FontSize=nodeFontSize)
else
drawNode(Ax,Layout.Positions(k,:),Layout.Labels(k),Style,Width=Layout.NodeWidth,Height=Layout.NodeHeight,EdgeColor=GetSeriesColor(Ax,Style.TreeLeafNodeSeriesIndex),FontSize=nodeFontSize)
end
end
end
%%
function Layout = MakeRegressionTreeLayout(mdl)
arguments
mdl
end
numNodes = mdl.NumNodes;
children = mdl.Children;
parent = mdl.Parent;
depth = ones(numNodes,1);
for k = 2:numNodes
depth(k) = depth(parent(k)) + 1;
end
xOrder = nan(numNodes,1);
leafCount = 0;
AssignLeafOrder(1)
if leafCount == 1
x = 0.5*ones(numNodes,1);
else
x = 0.10 + 0.80*(xOrder - 1)/(leafCount - 1);
end
maxDepth = max(depth);
if maxDepth == 1
y = 0.50*ones(numNodes,1);
else
y = 0.88 - 0.68*(depth - 1)/(maxDepth - 1);
end
labels = strings(numNodes,1);
for k = 1:numNodes
if mdl.IsBranchNode(k)
labels(k) = "x < " + compose("%.1f",mdl.CutPoint(k));
else
labels(k) = compose("%.0f",mdl.NodeMean(k));
end
end
nodeWidth = max(0.09,min(0.20,0.95/max(leafCount,5)));
nodeHeight = 0.08;
if leafCount > 8
nodeWidth = max(0.075,0.80/leafCount);
end
if maxDepth > 4
nodeHeight = 0.07;
end
Layout = struct("Positions",[x y], ...
"Labels",labels, ...
"NodeWidth",nodeWidth, ...
"NodeHeight",nodeHeight, ...
"NumLeaves",leafCount, ...
"NumNodes",numNodes);
function AssignLeafOrder(nodeIndex)
if nodeIndex == 0
return
end
if ~mdl.IsBranchNode(nodeIndex)
leafCount = leafCount + 1;
xOrder(nodeIndex) = leafCount;
return
end
leftChild = children(nodeIndex,1);
rightChild = children(nodeIndex,2);
AssignLeafOrder(leftChild)
AssignLeafOrder(rightChild)
childNodes = children(nodeIndex,children(nodeIndex,:) > 0);
xOrder(nodeIndex) = mean(xOrder(childNodes));
end
end
%%
function s = pluralS(n)
arguments
n (1,1) double
end
if n == 1
s = "";
else
s = "s";
end
end
%%
function CheckAnswer(exerciseID,option)
arguments
exerciseID (1,1) string
option
end
Exercises = struct();
ExerciseTree = MakeExerciseTreeSpec();
ExerciseState = EvaluateInteractiveTree(ExerciseTree,ExerciseTree.ExampleHour,ExerciseTree.ExampleTemperature);
Exercises.Exercise1 = struct("Answer",ExerciseState.Prediction,"Hint","Start at the root and follow the split conditions in order. Use the hour branch first, then apply the temperature rule only if that branch continues.");
Exercises.Exercise2 = struct("Answer","Regression Tree","Hint","Which model is designed to split the data into local regions or rules?");
Exercises.Exercise3 = struct("Answer","Ensemble of Trees","Hint","Which model combines many trees to improve accuracy on complex, noisy data?");
ExerciseName = char(exerciseID);
if ~isfield(Exercises,ExerciseName)
return
end
CorrectAnswer = Exercises.(ExerciseName).Answer;
HintText = Exercises.(ExerciseName).Hint;
if isequal(option,"Select")
return
elseif isequal(option,CorrectAnswer)
disp("You are correct.")
else
disp("Hint: " + HintText)
end
end
%%
function CheckPatternModelMatch(selection)
arguments
selection (1,4) string
end
correctSelection = ["Linear Regression","Stepwise Regression","Ensemble of Trees","Regression Tree"];
if any(selection == "Select")
warning("Select one model in each row.");
elseif isequal(selection,correctSelection)
disp("You are correct.")
else
disp("Not quite. Match the rows to the pattern type: linear, smooth nonlinear, threshold-based, or complex and noisy.")
end
end
%%
function drawNode(Ax,pos,label,Style,options)
arguments
Ax
pos (1,2) double
label
Style (1,1) struct
options.Highlight (1,1) logical = false
options.Width (1,1) double = 0.18
options.Height (1,1) double = 0.08
options.EdgeColor double = []
options.FaceColor double = []
options.FontSize (1,1) double = Style.TreeNodeFontSize
options.Interpreter = "latex"
options.Padding (1,2) double = [0.018 0.016]
options.Kind string = "branch"
options.CriterionAbove (1,1) logical = false
end
axesBackgroundColor = GetAxesBackgroundColor(Ax);
edgeColor = GetSeriesColor(Ax,Style.TreeNodeEdgeSeriesIndex);
faceColor = axesBackgroundColor;
lineWidth = 1.2;
if options.Highlight
edgeColor = GetSeriesColor(Ax,Style.TreeNodeHighlightSeriesIndex);
faceColor = BlendTowardBackground(edgeColor,axesBackgroundColor,0.82);
lineWidth = 2;
end
if ~isempty(options.EdgeColor)
edgeColor = options.EdgeColor;
end
if ~isempty(options.FaceColor)
faceColor = options.FaceColor;
end
interpreter = "latex";
nodeLabel = string(label);
criterionLabel = "";
if options.CriterionAbove
criterionLabel = nodeLabel;
nodeLabel = "$\mathrm{SPLIT}$";
elseif options.Kind == "leaf" && ~isnan(str2double(nodeLabel))
nodeLabel = "$\mathbf{" + nodeLabel + "}\ \mathrm{MW}$";
end
labelExtent = MeasureTextExtent(Ax,pos,nodeLabel,options.FontSize,interpreter);
xPad = options.Padding(1) * abs(diff(xlim(Ax)));
yPad = options.Padding(2) * abs(diff(ylim(Ax)));
nodeWidth = max(options.Width,labelExtent(3) + 2*xPad);
nodeHeight = max(options.Height,labelExtent(4) + 2*yPad);
rectangle(Ax,Position=[pos(1)-nodeWidth/2 pos(2)-nodeHeight/2 nodeWidth nodeHeight],EdgeColor=edgeColor,FaceColor=faceColor,LineWidth=lineWidth,Curvature=0.1,Clipping="off")
text(Ax,pos(1),pos(2),nodeLabel,HorizontalAlignment="center",VerticalAlignment="middle",FontWeight="bold",FontSize=options.FontSize,Interpreter=interpreter,Clipping="off")
if strlength(criterionLabel) > 0
criterionOffset = nodeHeight/2 + 1.5*yPad;
drawBranchLabel(Ax,[pos(1) pos(2) + criterionOffset],criterionLabel,Style, ...
FontSize=options.FontSize,Interpreter="latex")
end
end
%%
function drawBranchLabel(Ax,pos,label,Style,options)
arguments
Ax
pos (1,2) double
label
Style (1,1) struct
options.FontSize (1,1) double = Style.TreeBranchLabelFontSize
options.Interpreter = "latex"
options.Padding (1,2) double = [0.012 0.014]
end
interpreter = char(options.Interpreter);
labelExtent = MeasureTextExtent(Ax,pos,string(label),options.FontSize,interpreter);
xPad = options.Padding(1) * abs(diff(xlim(Ax)));
yPad = options.Padding(2) * abs(diff(ylim(Ax)));
labelWidth = labelExtent(3) + 2*xPad;
labelHeight = labelExtent(4) + 2*yPad;
labelBackgroundColor = GetAxesBackgroundColor(Ax);
labelEdgeColor = BlendTowardBackground(GetSeriesColor(Ax,Style.TreeBackgroundSeriesIndex),labelBackgroundColor,0.85);
rectangle(Ax,Position=[pos(1)-labelWidth/2 pos(2)-labelHeight/2 labelWidth labelHeight],EdgeColor=labelEdgeColor,FaceColor=labelBackgroundColor,Curvature=0.12,Clipping="off")
text(Ax,pos(1),pos(2),string(label),HorizontalAlignment="center",VerticalAlignment="middle",FontWeight="bold",FontSize=options.FontSize,Interpreter=interpreter,Clipping="off")
end
%%
function extent = MeasureTextExtent(Ax,pos,label,fontSize,interpreter)
tempText = text(Ax,pos(1),pos(2),string(label),HorizontalAlignment="center",VerticalAlignment="middle",FontSize=fontSize,Interpreter=interpreter,Visible="off",Clipping="off");
extent = tempText.Extent;
delete(tempText)
end
%%
function fig = ShowStaticTreeDiagram(TreeSpec,Style,options)
arguments
TreeSpec (1,1) struct
Style (1,1) struct = DefaultPlotStyle()
options.FigureName string = "Decision Tree Diagram"
options.FigureSize (1,2) double = [820 360]
options.ShowTitle (1,1) logical = true
end
fig = figure(Name=char(options.FigureName));
fig.Units = "pixels";
fig.Position(3:4) = options.FigureSize;
ax = axes(fig,Position=[0.05 0.08 0.90 0.84]);
ApplyDefaultAxesStyle(ax,Style)
RenderTreeDiagram(ax,TreeSpec,Style,ShowTitle=options.ShowTitle)
set(groot,"CurrentFigure",[])
end
%%
function RenderTreeDiagram(Ax,TreeSpec,Style,options)
arguments
Ax
TreeSpec (1,1) struct
Style (1,1) struct = DefaultPlotStyle()
options.HighlightNodeNames = strings(0,1)
options.HighlightBranchNames = strings(0,1)
options.ShowTitle (1,1) logical = true
options.NodeFontSize (1,1) double = Style.TreeNodeFontSize
options.BranchLabelFontSize (1,1) double = Style.TreeBranchLabelFontSize
options.AutoLayout (1,1) logical = true
end
if options.AutoLayout
TreeSpec = LayoutTreeSpec(TreeSpec);
end
cla(Ax)
hold(Ax,"on")
axis(Ax,"off")
xlim(Ax,TreeSpec.XLim)
ylim(Ax,TreeSpec.YLim)
ApplyDefaultAxesStyle(Ax,Style)
if options.ShowTitle && isfield(TreeSpec,"Title") && strlength(string(TreeSpec.Title)) > 0
title(Ax,string(TreeSpec.Title),Interpreter=char(Style.Interpreter))
end
for k = 1:numel(TreeSpec.Branches)
PlotNamedTreeBranch(Ax,TreeSpec,TreeSpec.Branches(k).Name,Style,false)
end
for k = 1:numel(options.HighlightBranchNames)
PlotNamedTreeBranch(Ax,TreeSpec,options.HighlightBranchNames(k),Style,true)
end
for k = 1:numel(TreeSpec.Nodes)
node = TreeSpec.Nodes(k);
nodeName = string(node.Name);
nodeWidth = 0.22;
nodeHeight = 0.11;
nodeInterpreter = "latex";
if isfield(node,"Width") && ~isnan(node.Width)
nodeWidth = node.Width;
end
if isfield(node,"Height") && ~isnan(node.Height)
nodeHeight = node.Height;
end
if isfield(node,"Interpreter") && strlength(string(node.Interpreter)) > 0
nodeInterpreter = string(node.Interpreter);
end
nodeKind = string(node.Kind);
isCriterion = nodeKind == "branch" && contains(string(node.Label),["<" ">" "="]);
if nodeKind == "leaf"
edgeColor = GetSeriesColor(Ax,Style.TreeLeafNodeSeriesIndex);
nodeWidth = max(nodeWidth,0.26);
nodeHeight = max(nodeHeight,0.14);
else
edgeColor = GetSeriesColor(Ax,Style.TreeBranchNodeSeriesIndex);
end
drawNode(Ax,node.Position,node.Label,Style, ...
Highlight=any(string(options.HighlightNodeNames) == nodeName), ...
Width=nodeWidth, ...
Height=nodeHeight, ...
EdgeColor=edgeColor, ...
FontSize=max(options.NodeFontSize,12), ...
Interpreter=nodeInterpreter, ...
Kind=nodeKind, ...
CriterionAbove=isCriterion)
end
for k = 1:numel(TreeSpec.Branches)
branch = TreeSpec.Branches(k);
if strlength(string(branch.Label)) == 0
continue
end
drawBranchLabel(Ax,branch.LabelPosition,branch.Label,Style,FontSize=options.BranchLabelFontSize)
end
end
%%
function TreeSpec = LayoutTreeSpec(TreeSpec)
nodeNames = string({TreeSpec.Nodes.Name});
nodeCount = numel(TreeSpec.Nodes);
parentIndex = zeros(nodeCount,1);
children = cell(nodeCount,1);
for branchIndex = 1:numel(TreeSpec.Branches)
branch = TreeSpec.Branches(branchIndex);
startIndex = find(nodeNames == string(branch.StartNode),1);
endIndex = find(nodeNames == string(branch.EndNode),1);
parentIndex(endIndex) = startIndex;
children{startIndex}(end + 1) = endIndex;
end
rootIndex = find(parentIndex == 0,1);
depth = nan(nodeCount,1);
depth(rootIndex) = 0;
pending = rootIndex;
while ~isempty(pending)
nodeIndex = pending(1);
pending(1) = [];
childIndices = children{nodeIndex};
depth(childIndices) = depth(nodeIndex) + 1;
pending = [pending childIndices]; %#ok<AGROW>
end
leafIndices = find(cellfun(@isempty,children));
xRange = TreeSpec.XLim;
yRange = TreeSpec.YLim;
xMargin = 0.10 * diff(xRange);
yMargin = 0.12 * diff(yRange);
leafX = linspace(xRange(1) + xMargin,xRange(2) - xMargin,numel(leafIndices));
xPositions = nan(nodeCount,1);
xPositions(leafIndices) = leafX;
assignNodeX(rootIndex)
maxDepth = max(depth);
if maxDepth == 0
yPositions = mean(yRange) * ones(nodeCount,1);
else
yPositions = yRange(2) - yMargin - depth / maxDepth * (diff(yRange) - 2 * yMargin);
end
for nodeIndex = 1:nodeCount
TreeSpec.Nodes(nodeIndex).Position = [xPositions(nodeIndex) yPositions(nodeIndex)];
end
for branchIndex = 1:numel(TreeSpec.Branches)
branch = TreeSpec.Branches(branchIndex);
startIndex = find(nodeNames == string(branch.StartNode),1);
endIndex = find(nodeNames == string(branch.EndNode),1);
midpoint = mean([TreeSpec.Nodes(startIndex).Position; TreeSpec.Nodes(endIndex).Position],1);
TreeSpec.Branches(branchIndex).LabelPosition = midpoint + [0 0.035 * diff(yRange)];
end
function xPosition = assignNodeX(nodeIndex)
if ~isnan(xPositions(nodeIndex))
xPosition = xPositions(nodeIndex);
return
end
childIndices = children{nodeIndex};
childX = zeros(size(childIndices));
for childIndex = 1:numel(childIndices)
childX(childIndex) = assignNodeX(childIndices(childIndex));
end
xPosition = mean(childX);
xPositions(nodeIndex) = xPosition;
end
end
%%
function PlotNamedTreeBranch(Ax,TreeSpec,BranchName,Style,highlighted)
arguments
Ax
TreeSpec (1,1) struct
BranchName
Style (1,1) struct = DefaultPlotStyle()
highlighted (1,1) logical = false
end
branch = GetTreeBranch(TreeSpec,BranchName);
[startPos,endPos] = GetTreeBranchEndpoints(TreeSpec,branch);
if highlighted
plot(Ax,[startPos(1) endPos(1)],[startPos(2) endPos(2)],LineWidth=Style.TreeHighlightLineWidth,SeriesIndex=Style.TreeHighlightSeriesIndex)
else
plot(Ax,[startPos(1) endPos(1)],[startPos(2) endPos(2)],":",LineWidth=Style.TreeBackgroundLineWidth,SeriesIndex=Style.TreeBackgroundSeriesIndex)
end
end
%%
function [startPos,endPos] = GetTreeBranchEndpoints(TreeSpec,branch)
startNode = GetTreeNode(TreeSpec,branch.StartNode);
endNode = GetTreeNode(TreeSpec,branch.EndNode);
startPos = startNode.Position;
endPos = endNode.Position;
end
%%
function node = GetTreeNode(TreeSpec,nodeName)
nodeNames = string({TreeSpec.Nodes.Name});
matchIndex = find(nodeNames == string(nodeName),1);
node = TreeSpec.Nodes(matchIndex);
end
%%
function branch = GetTreeBranch(TreeSpec,branchName)
branchNames = string({TreeSpec.Branches.Name});
matchIndex = find(branchNames == string(branchName),1);
branch = TreeSpec.Branches(matchIndex);
end
%%
function TreeSpec = MakeTreeTerminologySpec()
TreeSpec = struct();
TreeSpec.Title = "Parts of a Decision Tree";
TreeSpec.XLim = [0.04 0.96];
TreeSpec.YLim = [0.08 0.92];
TreeSpec.Nodes = [ ...
MakeTreeNode("Root",[0.50 0.79],"Root node","branch"), ...
MakeTreeNode("LeftLeaf",[0.24 0.50],"Leaf node","leaf"), ...
MakeTreeNode("RightNode",[0.76 0.53],"Internal node","branch"), ...
MakeTreeNode("RightLeftLeaf",[0.60 0.22],"Leaf node","leaf"), ...
MakeTreeNode("RightRightLeaf",[0.86 0.22],"Leaf node","leaf")];
TreeSpec.Branches = [ ...
MakeTreeBranch("RootLeft","Root","LeftLeaf","yes",[0.35 0.67]), ...
MakeTreeBranch("RootRight","Root","RightNode","no",[0.66 0.68]), ...