Random math function

In SymbolicRegression.jl, you can do this:

using SymbolicRegression

# Define the available operators:
options = Options(;
    binary_operators=(+, -, *, /, ^),
    unary_operators=(cos, sin, exp),
)

First, let’s construct a tree manually:

x1, x2, x3 = Node("x1"), Node("x2"), Node("x3")
tree = x1 - x2 * 3.2

println(tree)
# (x1 - (x2 * 3.2))

Now, let’s generate it randomly. Let’s say we want 5 nodes total. Say that we have 3 feature nodes to use (and any number of constant nodes). We also specify the type of constants in a given tree:

num_nodes = 5
num_features = 3
type = Float64
tree = gen_random_tree_fixed_size(num_nodes, options, num_features, type)
println(tree)
# exp(cos(x3) + 0.1950986787131656)

We can also evaluate the tree over an array:

# Evaluate the tree:
X = randn(Float64, 3, 1000);
out, did_complete = eval_tree_array(tree, X, options)

And do other things like counting nodes, constants, etc.:

count_nodes(tree)
# ^ 5
2 Likes