random expression generation

158 views
Skip to first unread message

Gasper Slapnicar

unread,
Jul 25, 2016, 9:22:31 AM7/25/16
to sympy
Hello everyone.

I am rather new to both symbolic regression and sympy. I am trying to use expressions (mathematical equations) to represent individuals in a genetic algorithm population. However, i came across the following issue:

When trying to create an initial population, i have to create equations/expressions/trees from a fixed set of Symbols and operations. I do not know how to combine them into random combinations representing complete expression trees.
Here is my code snippet:
# Symbols
x1, x2 = symbols('x1, x2')
# Functions
operations = [Add, Mul, Rational, Pow, sin, cos, tanh, log]
for i in xrange(100):
random_operation = randint(0, 7)
print operations[random_operation]

With this i manage to get a random operation as described here: http://docs.sympy.org/dev/tutorial/manipulation.html

However, i would like to create complete examples of equations/expressions/trees, including my symbols, so that i can represent them as trees. My ultimate goal is to evolve this population by substituting certain operations/symbols for the new population (crossover, mutation, etc). For example, i would like to have (many different random combinations):
>>> expr = (Symbol('x1')+Symbol('x2'))**2 / 3
>>> srepr(expr)
Mul(Rational(1,3),Pow(Add(Symbol(x1),Symbol(x2)),Integer(2)))

Any help much appreciated.

Thank you and kind regards,
Gasper

Richard Fateman

unread,
Jul 25, 2016, 10:14:35 AM7/25/16
to sympy
This strikes me as a rather weak idea from a genetic algorithms point of view.

but you can create expressions by a recursive algorithm  (given some chosen maximum length) from the root
by picking an operation at each level, knowing the number of operands each takes.

Francesco Bonazzi

unread,
Jul 25, 2016, 5:00:21 PM7/25/16
to sympy
By just looking up on google:

http://mathematica.stackexchange.com/questions/11632/how-to-generate-a-random-tree

Anyway, if you do go on with your code, would you feel like sharing it? We could merge into SymPy a random expression generator, it can always be useful.

Easiest way, recursive function picking a random element each time. If it's an atom, stop, otherwise call the function recursively on the children elements.

You could easily store your node elements in a dictionary, telling you how many children there are.

Francesco Bonazzi

unread,
Jul 25, 2016, 5:03:22 PM7/25/16
to sympy
Reply all
Reply to author
Forward
0 new messages