DEAP / deap

Distributed Evolutionary Algorithms in Python
http://deap.readthedocs.org/
GNU Lesser General Public License v3.0
5.84k stars 1.13k forks source link

DEAP-Symbolic Regression Tutorial Example- How to Plot final best Individual? #564

Open OUStudent opened 3 years ago

OUStudent commented 3 years ago

So I just went through the Symbolic Regression Tutorial Example (https://deap.readthedocs.io/en/master/examples/gp_symbreg.html).

The problem is that at the very end it does not show you how to 'plot'/graph the best individual. How can I do this? I know the example code tracks the 1 best individual from every generation in HOF, so I know that's the individual I want to plot but how can I do this?

I looked at this page (https://deap.readthedocs.io/en/master/tutorials/advanced/gp.html) and it seems you can do this through: expr = gp.genFull(pset, min=1, max=90) tree = gp.PrimitiveTree(expr) str(tree) So I added that right before the main function returned pop, log, hof and I get a memory error... is there any way I can generate the graph/tree?

aymericvie commented 3 years ago

Hi!

I noticed a related issue in a previous Issue.

At the end of the SR code:

bests = tools.selBest(pop, k=1)
print(bests[0])

Will give you the sort of pseudo code of the best individual as a deap.creator.Individual object.

add(mul(x, add(mul(sub(protectedDiv(x, x), neg(x)), mul(x, x)), x)), x)

To plot it, I used the following:


    import pygraphviz as pgv
    import matplotlib.pyplot as plt
    import networkx

    nodes, edges, labels = gp.graph(bests[0])
    graph = networkx.Graph()
    graph.add_nodes_from(nodes)
    graph.add_edges_from(edges)
    #pos = graphviz_layout(graph, prog='dot')
    pos = nx.nx_agraph.graphviz_layout(graph, prog="dot")

    plt.figure(figsize=(7,7))
    networkx.draw_networkx_nodes(graph, pos, node_size=900, node_color="w")
    networkx.draw_networkx_edges(graph, pos)
    networkx.draw_networkx_labels(graph, pos, labels)
    plt.axis("off")
    plt.show()

To finally obtain: GP_end

In short, I am passing through networkx to plot the tree.

VeiledTee commented 3 years ago

Hey!

I've been having issue with the pygraphviz and networkx installs, do you know of any other way to generate this tree? Or even if there's a way to interpret and plot the add(mul(x, add(mul(sub(protectedDiv(x, x), neg(x)), mul(x, x)), x)), x) output to a matplotlib plot? I'm working on a report for an evolutionary computation course and would really like to generate some 'pretty pictures' (for lack of a better term) for it.

Cheers!