|
5 | 5 | # Node and Tree Operations |
6 | 6 |
|
7 | 7 | This example demonstrates how to create and manipulate expression trees |
8 | | - using the [`Node`](@ref) type. We'll create a tree, |
9 | | - perform various operations, and show how to traverse and modify it. |
| 8 | + using the [`Node`](@ref) type. |
10 | 9 |
|
11 | | - First, let's create a simple expression tree. |
12 | | - We can bootstrap this by creating a node to hold `feature=1`, |
13 | | - indicating the first input variable (first column of data): |
| 10 | + First, let's create a node to reference `feature=1` of our dataset: |
14 | 11 | =# |
15 | 12 | using DynamicExpressions, Random |
16 | 13 |
|
|
72 | 69 |
|
73 | 70 | Let's see an example. Say we just want to count the nodes in the tree: |
74 | 71 | =# |
75 | | - tree_mapreduce(node -> 1, +, tree) |
| 72 | + num_nodes = tree_mapreduce(node -> 1, +, tree) |
| 73 | + @test num_nodes == 8 #src |
76 | 74 | #= |
77 | 75 | Here, the `+` handles both the cases of 1 child and 2 children. |
78 | 76 | Here, we didn't need to specify a custom branch function, but we could do that too: |
79 | 77 | =# |
80 | | - tree_mapreduce(leaf_node -> 1, branch_node -> 0, +, tree) |
| 78 | + num_leafs = tree_mapreduce(leaf_node -> 1, branch_node -> 0, +, tree) |
| 79 | + @test num_leafs == 4 #src |
81 | 80 | #= |
82 | 81 | This counts the number of leaf nodes in the tree. For `tree`, |
83 | 82 | this was `x`, `y`, `const_1`, and `x`. |
|
93 | 92 | As a more complex example, let's compute the depth of a tree. Here, we need |
94 | 93 | to use a more complicated reduction operation – the `max`: |
95 | 94 | =# |
96 | | - tree_mapreduce( |
| 95 | + depth = tree_mapreduce( |
97 | 96 | node -> 1, (parent, children...) -> 1 + max(children...), x + sin(sin(exp(x))) |
98 | 97 | ) |
| 98 | + @test depth == 5 #src |
99 | 99 | #= |
100 | 100 | Here, the `max` handles both the cases of 1 child and 2 children. |
101 | 101 | The parent node contributes `1` at each depth. Note that the inputs |
|
0 commit comments