|
| 1 | +"""\ |
| 2 | +Feed-forward LunarLander-v3 control example. |
| 3 | +
|
| 4 | +This example is structured similarly to examples/xor/evolve-feedforward.py and |
| 5 | +produces the same kinds of visual artifacts: |
| 6 | +
|
| 7 | +* Fitness curve over generations |
| 8 | +* Species size stack plot |
| 9 | +* Network diagrams (full and pruned) of the winning genome |
| 10 | +""" |
| 11 | + |
| 12 | +import multiprocessing |
| 13 | +import os |
| 14 | +import pickle |
| 15 | + |
| 16 | +import gymnasium as gym |
| 17 | +import neat |
| 18 | +import visualize |
| 19 | + |
| 20 | +# Evaluation parameters. |
| 21 | +runs_per_net = 5 |
| 22 | +max_steps = 1000 |
| 23 | + |
| 24 | + |
| 25 | +def eval_genome(genome, config): |
| 26 | + """Evaluate a single genome on the LunarLander-v3 environment.""" |
| 27 | + net = neat.nn.FeedForwardNetwork.create(genome, config) |
| 28 | + fitnesses = [] |
| 29 | + |
| 30 | + for _ in range(runs_per_net): |
| 31 | + # Create a fresh environment for each run (no rendering during training). |
| 32 | + env = gym.make("LunarLander-v3") |
| 33 | + observation, info = env.reset() |
| 34 | + |
| 35 | + total_reward = 0.0 |
| 36 | + for _ in range(max_steps): |
| 37 | + # Network outputs four action values; take the argmax as the discrete action. |
| 38 | + action_values = net.activate(observation) |
| 39 | + action = max(range(len(action_values)), key=lambda i: action_values[i]) |
| 40 | + |
| 41 | + observation, reward, terminated, truncated, info = env.step(action) |
| 42 | + total_reward += reward |
| 43 | + |
| 44 | + if terminated or truncated: |
| 45 | + break |
| 46 | + |
| 47 | + env.close() |
| 48 | + fitnesses.append(total_reward) |
| 49 | + |
| 50 | + # Use the average reward over runs as the fitness. |
| 51 | + return sum(fitnesses) / len(fitnesses) |
| 52 | + |
| 53 | + |
| 54 | +def eval_genomes(genomes, config): |
| 55 | + for genome_id, genome in genomes: |
| 56 | + genome.fitness = eval_genome(genome, config) |
| 57 | + |
| 58 | + |
| 59 | +def run(config_file): |
| 60 | + # Load configuration. |
| 61 | + config = neat.Config( |
| 62 | + neat.DefaultGenome, |
| 63 | + neat.DefaultReproduction, |
| 64 | + neat.DefaultSpeciesSet, |
| 65 | + neat.DefaultStagnation, |
| 66 | + config_file, |
| 67 | + ) |
| 68 | + |
| 69 | + # Create the population, which is the top-level object for a NEAT run. |
| 70 | + p = neat.Population(config) |
| 71 | + |
| 72 | + # Add a stdout reporter to show progress in the terminal. |
| 73 | + p.add_reporter(neat.StdOutReporter(True)) |
| 74 | + stats = neat.StatisticsReporter() |
| 75 | + p.add_reporter(stats) |
| 76 | + # Periodic checkpoints, similar to other examples. |
| 77 | + p.add_reporter(neat.Checkpointer(10)) |
| 78 | + |
| 79 | + # Use parallel evaluation across available CPU cores. |
| 80 | + pe = neat.ParallelEvaluator(multiprocessing.cpu_count(), eval_genome) |
| 81 | + |
| 82 | + # Run until solution or fitness threshold is reached (see config). |
| 83 | + winner = p.run(pe.evaluate, 500) |
| 84 | + |
| 85 | + # Display the winning genome. |
| 86 | + print(f"\nBest genome:\n{winner!s}") |
| 87 | + |
| 88 | + # Save the winner for later reuse in test-feedforward.py. |
| 89 | + with open("winner-feedforward.pickle", "wb") as f: |
| 90 | + pickle.dump(winner, f) |
| 91 | + |
| 92 | + # Visualization artifacts analogous to examples/xor/evolve-feedforward.py. |
| 93 | + # Fitness & species plots. |
| 94 | + visualize.plot_stats( |
| 95 | + stats, |
| 96 | + ylog=False, |
| 97 | + view=True, |
| 98 | + filename="feedforward-fitness.svg", |
| 99 | + ) |
| 100 | + visualize.plot_species( |
| 101 | + stats, |
| 102 | + view=True, |
| 103 | + filename="feedforward-speciation.svg", |
| 104 | + ) |
| 105 | + |
| 106 | + # Node labels for easier interpretation of the evolved controller. |
| 107 | + node_names = { |
| 108 | + # Observations |
| 109 | + -1: "x", |
| 110 | + -2: "y", |
| 111 | + -3: "x_dot", |
| 112 | + -4: "y_dot", |
| 113 | + -5: "angle", |
| 114 | + -6: "ang_vel", |
| 115 | + -7: "left_leg", |
| 116 | + -8: "right_leg", |
| 117 | + # Discrete actions |
| 118 | + 0: "do_nothing", |
| 119 | + 1: "fire_left", |
| 120 | + 2: "fire_main", |
| 121 | + 3: "fire_right", |
| 122 | + } |
| 123 | + |
| 124 | + # Full and pruned network diagrams for the winning genome. |
| 125 | + visualize.draw_net( |
| 126 | + config, |
| 127 | + winner, |
| 128 | + view=True, |
| 129 | + node_names=node_names, |
| 130 | + filename="winner-feedforward.gv", |
| 131 | + ) |
| 132 | + visualize.draw_net( |
| 133 | + config, |
| 134 | + winner, |
| 135 | + view=True, |
| 136 | + node_names=node_names, |
| 137 | + filename="winner-feedforward-pruned.gv", |
| 138 | + prune_unused=True, |
| 139 | + ) |
| 140 | + |
| 141 | + return winner, stats |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == "__main__": |
| 145 | + # Determine path to configuration file. This path manipulation is |
| 146 | + # here so that the script will run successfully regardless of the |
| 147 | + # current working directory. |
| 148 | + local_dir = os.path.dirname(__file__) |
| 149 | + config_path = os.path.join(local_dir, "config-feedforward") |
| 150 | + run(config_path) |
0 commit comments