### Install example dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/hopper/README.md Install all required packages for the example using the provided requirements file. ```bash pip install -r examples/requirements.txt ``` -------------------------------- ### Install All Example Dependencies (Comprehensive) Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Installs a comprehensive set of Python packages required for all NEAT-Python examples, including visualization, control, and interactive features. ```bash # For all examples pip install graphviz matplotlib "gymnasium[box2d,mujoco]" numpy pygame gizeh moviepy ``` -------------------------------- ### Install Specific Dependencies for Gymnasium Control Examples Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Installs specific Python packages for Gymnasium control examples, including box2d and mujoco, along with numpy. ```bash # For Gymnasium control examples (LunarLander, BipedalWalker, InvertedDoublePendulum) pip install "gymnasium[box2d,mujoco]" numpy ``` -------------------------------- ### Install Specific Dependencies for Interactive/Video Examples Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Installs specific Python packages for interactive and video-based examples, such as picture2d and cart-pole movie. ```bash # For interactive / video examples (picture2d, cart-pole movie) pip install pygame gizeh moviepy ``` -------------------------------- ### Install All Dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/export/README.md Install all necessary dependencies for PyTorch, TensorFlow, and ONNX support at once. ```bash # Or install everything at once pip install torch tensorflow onnxscript ``` -------------------------------- ### Complete Reproducible XOR Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/reproducibility.md A full example demonstrating a reproducible XOR problem solution using NEAT. It includes setup, fitness evaluation, and verification of reproducibility by running the experiment twice with the same seed. ```python import os import neat # XOR inputs and expected outputs xor_inputs = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)] xor_outputs = [(0.0,), (1.0,), (1.0,), (0.0,)] def eval_genomes(genomes, config): for genome_id, genome in genomes: genome.fitness = 4.0 net = neat.nn.FeedForwardNetwork.create(genome, config) for xi, xo in zip(xor_inputs, xor_outputs): output = net.activate(xi) genome.fitness -= (output[0] - xo[0]) ** 2 def run(): # Load configuration local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, 'config-xor') config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path) # Run with seed for reproducibility pop = neat.Population(config, seed=42) pop.add_reporter(neat.StdOutReporter(True)) winner = pop.run(eval_genomes, 300) print(f"\nWinner fitness: {winner.fitness:.6f}") return winner if __name__ == '__main__': # Run twice - should get identical results winner1 = run() winner2 = run() assert winner1.fitness == winner2.fitness print("\n✓ Results are reproducible!") ``` -------------------------------- ### Install minimal dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/hopper/README.md Install only the core packages required to run the Hopper-v5 example. ```bash pip install neat-python gymnasium[mujoco] ``` -------------------------------- ### Install neat-python from Source Source: https://github.com/codereclaimers/neat-python/blob/master/docs/installation.md Install neat-python using pip after cloning the repository or downloading the source archive. ```bash pip install . ``` -------------------------------- ### Initialize Ray for distributed computing Source: https://github.com/codereclaimers/neat-python/blob/master/docs/migration.md Example setup for using Ray as an alternative for multi-machine distributed fitness evaluation. ```python import neat import ray ``` -------------------------------- ### Install Dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/inverted-double-pendulum/README.md Install the required packages for running the NEAT-Python evolution and the Gymnasium environment. ```bash pip install neat-python gymnasium ``` ```bash pip install pygame ``` -------------------------------- ### Install Dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/export/README.md Commands to install the necessary deep learning frameworks for model conversion. ```bash pip install torch # for PyTorch/ONNX pip install tensorflow # for TensorFlow ``` -------------------------------- ### Run Export Example Script Source: https://github.com/codereclaimers/neat-python/blob/master/examples/export/README.md Execute the export example script to train a simple XOR network and generate a JSON file representing the exported network. ```bash python export_example.py ``` -------------------------------- ### Install visualization dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/hopper/README.md Install pygame to enable real-time environment visualization. ```bash pip install pygame ``` -------------------------------- ### Start Evolution with Simpler Network Configurations Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Initialize NEAT with no hidden nodes and fully connect input nodes to output nodes. This provides a simpler starting point, reducing the initial complexity and allowing complexity to grow more gradually if needed. ```ini [DefaultGenome] num_hidden = 0 # Start with no hidden nodes initial_connection = full # Fully connect inputs to outputs ``` -------------------------------- ### Build and Test Commands Source: https://github.com/codereclaimers/neat-python/blob/master/AGENTS.md Common commands for installing, testing, and building documentation for neat-python. ```bash # Install in development mode pip install -e . # Run the test suite python -m pytest tests/ # Run a specific example cd examples/xor python evolve_feedforward.py # Build documentation locally cd docs make html ``` -------------------------------- ### Minimal Complete Configuration Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/migration.md A minimal configuration file for a feedforward network solving XOR in v1.0. It includes essential parameters for the [NEAT] and [DefaultGenome] sections. ```ini [NEAT] fitness_criterion = max fitness_threshold = 0.9 pop_size = 150 reset_on_extinction = False no_fitness_termination = False [DefaultGenome] # Node activation options activation_default = sigmoid activation_mutate_rate = 0.0 activation_options = sigmoid # Node aggregation options aggregation_default = sum aggregation_mutate_rate = 0.0 aggregation_options = sum # Node bias options bias_init_mean = 0.0 bias_init_stdev = 1.0 bias_init_type = gaussian bias_max_value = 30.0 bias_min_value = -30.0 bias_mutate_power = 0.5 bias_mutate_rate = 0.7 bias_replace_rate = 0.1 # Genome compatibility options compatibility_disjoint_coefficient = 1.0 compatibility_weight_coefficient = 0.5 # Connection add/remove rates conn_add_prob = 0.5 conn_delete_prob = 0.5 # Connection enable options enabled_default = True enabled_mutate_rate = 0.01 enabled_rate_to_true_add = 0.0 enabled_rate_to_false_add = 0.0 # Network topology feed_forward = True initial_connection = full # Node add/remove rates node_add_prob = 0.2 node_delete_prob = 0.2 # Network parameters num_hidden = 0 num_inputs = 2 num_outputs = 1 # Node response options response_init_mean = 1.0 response_init_stdev = 0.0 response_init_type = gaussian response_max_value = 30.0 response_min_value = -30.0 response_mutate_power = 0.0 response_mutate_rate = 0.0 response_replace_rate = 0.0 # Structural mutation single_structural_mutation = false structural_mutation_surer = default ``` -------------------------------- ### Copy Visualize.py to Project Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Copies the 'visualize.py' script from the XOR example directory to the user's project directory. ```bash # Copy from XOR example cp examples/xor/visualize.py your_project/ ``` -------------------------------- ### NEAT-Python Evolution Output Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/quickstart.md Example output from a NEAT-Python evolution run, showing generation progress, population statistics, and the best genome found. ```text ****** Running generation 0 ****** Population's average fitness: 2.33450 stdev: 0.52901 Best fitness: 3.58932 - size: (2, 3) - species 1 - id 8 Average adjusted fitness: 0.291 Mean genetic distance 1.318, standard deviation 0.543 Population of 150 members in 3 species: ID age size fitness adj fit stag ==== === ==== ======= ======= ==== 1 0 86 3.589 0.306 0 2 0 32 3.013 0.289 0 3 0 32 2.945 0.279 0 Total extinctions: 0 Generation time: 0.024 sec ****** Running generation 50 ****** Population's average fitness: 3.89234 stdev: 0.08234 Best fitness: 3.98765 - size: (3, 5) - species 1 - id 1234 [Evolution continues...] ****** Running generation 73 ****** Best fitness: 3.96234 - size: (2, 4) - species 1 - id 2891 Best individual in generation 73 meets fitness threshold - complexity: (2, 4) Best genome: Key: 2891 Fitness: 3.96234 Nodes: 0 DefaultNodeGene(key=0, bias=-0.523, response=1.0, ... Connections: DefaultConnectionGene(key=(-1, 0), weight=4.832, enabled=True) DefaultConnectionGene(key=(-2, 0), weight=4.651, enabled=True) ``` -------------------------------- ### Install Optional Dependency Groups Source: https://github.com/codereclaimers/neat-python/blob/master/docs/installation.md Install neat-python with specific optional dependency groups for enhanced functionality. ```bash pip install 'neat-python[gpu]' ``` ```bash pip install 'neat-python[examples]' ``` ```bash pip install 'neat-python[docs]' ``` ```bash pip install 'neat-python[all]' ``` -------------------------------- ### Install neat-python from PyPI Source: https://github.com/codereclaimers/neat-python/blob/master/docs/installation.md Use this command to install the latest release of neat-python from the Python Package Index. ```bash pip install neat-python ``` -------------------------------- ### Install PyTorch Dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/export/README.md Install the PyTorch library, required for PyTorch model conversion. ```bash # For PyTorch support pip install torch ``` -------------------------------- ### Editable Install with Development Dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/docs/installation.md Install neat-python in editable mode with development tools for active development. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Annotated XOR Configuration Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/config_essentials.md A snippet of the XOR configuration file with inline comments explaining the purpose of specific parameters. ```ini [NEAT] # Use the highest fitness in the population as the criterion fitness_criterion = max # Stop evolution when a genome reaches this fitness # For XOR: 4.0 is perfect (no error), 3.9 is "good enough" fitness_threshold = 3.9 # Number of genomes (organisms) in each generation # More = slower but better exploration. 150 is good for simple problems. pop_size = 150 # Don't restart from scratch if all species go extinct # (Rarely happens with proper configuration) reset_on_extinction = False ``` -------------------------------- ### Install Matplotlib for Visualization Source: https://github.com/codereclaimers/neat-python/blob/master/examples/lorenz-ctrnn/README.md Installs the matplotlib library, which is required for generating optional PNG plots of the Lorenz attractor phase portrait and time series. ```bash pip install matplotlib ``` -------------------------------- ### Configure NEAT-Python for XOR Source: https://github.com/codereclaimers/neat-python/blob/master/docs/xor_example.md Configuration file defining the NEAT parameters, genome settings, and network structure for the XOR example. ```ini [NEAT] fitness_criterion = max fitness_threshold = 3.9 pop_size = 150 reset_on_extinction = False no_fitness_termination = False # Reproducibility: Uncomment to enable deterministic evolution # Useful for debugging, comparing algorithm variants, or scientific reproducibility # seed = 42 [DefaultGenome] # node activation options activation_default = sigmoid activation_mutate_rate = 0.0 activation_options = sigmoid # node aggregation options aggregation_default = sum aggregation_mutate_rate = 0.0 aggregation_options = sum # node bias options bias_init_mean = 0.0 bias_init_stdev = 1.0 bias_max_value = 30.0 bias_min_value = -30.0 bias_mutate_power = 0.5 bias_mutate_rate = 0.7 bias_replace_rate = 0.1 # genome compatibility options compatibility_disjoint_coefficient = 1.0 compatibility_weight_coefficient = 0.5 # connection add/remove rates conn_add_prob = 0.5 conn_delete_prob = 0.5 # connection enable options enabled_default = True enabled_mutate_rate = 0.01 feed_forward = True # Start with all inputs connected to all outputs. initial_connection = full_direct # node add/remove rates node_add_prob = 0.2 node_delete_prob = 0.2 # network parameters num_hidden = 0 num_inputs = 2 num_outputs = 1 # node response options response_init_mean = 1.0 response_init_stdev = 0.0 response_max_value = 30.0 response_min_value = -30.0 response_mutate_power = 0.0 response_mutate_rate = 0.0 response_replace_rate = 0.0 ``` -------------------------------- ### Minimal NEAT Configuration Template Source: https://github.com/codereclaimers/neat-python/blob/master/docs/config_essentials.md A complete, minimal working configuration file that can be used as a starting template for new projects. ```ini [NEAT] fitness_criterion = max fitness_threshold = 3.9 pop_size = 150 reset_on_extinction = False no_fitness_termination = False [DefaultGenome] # Network structure num_inputs = 2 num_outputs = 1 num_hidden = 0 feed_forward = True initial_connection = full_direct # Activation function activation_default = sigmoid activation_mutate_rate = 0.0 activation_options = sigmoid # Aggregation function aggregation_default = sum aggregation_mutate_rate = 0.0 aggregation_options = sum # Node bias options bias_init_mean = 0.0 bias_init_stdev = 1.0 bias_init_type = gaussian bias_max_value = 30.0 bias_min_value = -30.0 bias_mutate_power = 0.5 bias_mutate_rate = 0.7 bias_replace_rate = 0.1 # Genome compatibility options compatibility_disjoint_coefficient = 1.0 compatibility_weight_coefficient = 0.5 # Connection add/remove rates conn_add_prob = 0.5 conn_delete_prob = 0.5 # Connection enable options enabled_default = True enabled_mutate_rate = 0.01 enabled_rate_to_true_add = 0.0 enabled_rate_to_false_add = 0.0 # Node add/remove rates node_add_prob = 0.2 node_delete_prob = 0.2 # Node response options response_init_mean = 1.0 response_init_stdev = 0.0 response_init_type = gaussian response_max_value = 30.0 response_min_value = -30.0 response_mutate_power = 0.0 response_mutate_rate = 0.0 response_replace_rate = 0.0 # Connection weight options weight_init_mean = 0.0 weight_init_stdev = 1.0 weight_init_type = gaussian weight_max_value = 30 weight_min_value = -30 weight_mutate_power = 0.5 weight_mutate_rate = 0.8 weight_replace_rate = 0.1 # Structural mutation single_structural_mutation = false structural_mutation_surer = default [DefaultSpeciesSet] compatibility_threshold = 3.0 [DefaultStagnation] species_fitness_func = max max_stagnation = 20 species_elitism = 2 [DefaultReproduction] elitism = 2 survival_threshold = 0.2 min_species_size = 2 ``` -------------------------------- ### NEAT-Python Checkpointing Setup Source: https://github.com/codereclaimers/neat-python/blob/master/docs/cookbook.md Configure the Checkpointer reporter to save evolution progress at specified generation intervals. This allows resuming training from saved states. ```python import neat config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, 'config-file') p = neat.Population(config) p.add_reporter(neat.StdOutReporter(True)) # Save checkpoint every 5 generations checkpointer = neat.Checkpointer(generation_interval=5, time_interval_seconds=None, filename_prefix='neat-checkpoint-') p.add_reporter(checkpointer) # Run evolution winner = p.run(eval_genomes, 100) ``` -------------------------------- ### Clone neat-python Repository Source: https://github.com/codereclaimers/neat-python/blob/master/docs/installation.md Clone the source repository to obtain the latest code and examples. ```bash git clone https://github.com/CodeReclaimers/neat-python.git ``` -------------------------------- ### Install ONNX Dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/export/README.md Install ONNX and related libraries, which requires PyTorch and onnxscript for ONNX model conversion. ```bash # For ONNX (requires PyTorch + onnxscript) pip install torch onnxscript ``` -------------------------------- ### Canonical NEAT Configuration Template Source: https://github.com/codereclaimers/neat-python/blob/master/docs/academic_research.md A starting template for the configuration file to align neat-python with canonical NEAT standards. ```ini [NEAT] fitness_criterion = max fitness_threshold = pop_size = 150 reset_on_extinction = False [DefaultGenome] ``` -------------------------------- ### Missing Required Parameter Error Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/migration.md Illustrates the runtime error encountered when a required configuration parameter is missing. The error message provides specific guidance on the missing parameter and a suggested value. ```text RuntimeError: Missing required configuration item: 'bias_init_type' This parameter must be explicitly specified in your configuration file. Suggested value: bias_init_type = gaussian ``` -------------------------------- ### Configure NEAT parameters in INI format Source: https://github.com/codereclaimers/neat-python/blob/master/docs/config_file.md Example of defining population size and a random seed within the [NEAT] section of a configuration file. ```ini [NEAT] pop_size = 150 seed = 42 # Enable reproducibility ``` -------------------------------- ### Check NEAT-Python Version Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Print the currently installed version of the NEAT-Python library. This is crucial for diagnosing compatibility issues, especially when loading checkpoints from different versions. ```python import neat print(f"NEAT-Python version: {neat.__version__}") ``` -------------------------------- ### NEAT Network JSON Topology Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/network-json-format.md Defines the input and output structure of the network, specifying the number of inputs and outputs, and their corresponding node IDs. ```json { "num_inputs": 3, "num_outputs": 2, "input_keys": [-1, -2, -3], "output_keys": [0, 1] } ``` -------------------------------- ### Minimal NEAT-Python Example for XOR Source: https://github.com/codereclaimers/neat-python/blob/master/docs/quickstart.md Evolves a neural network to solve the XOR problem using NEAT-Python. This script defines the fitness function, loads configuration, runs the evolution, and prints the best genome. ```python import neat # XOR test cases: input -> expected output xor_inputs = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)] xor_outputs = [(0.0,), (1.0,), (1.0,), (0.0,)] def eval_genomes(genomes, config): """Fitness function: evaluates how well each genome solves XOR.""" for genome_id, genome in genomes: # Create a neural network from this genome net = neat.nn.FeedForwardNetwork.create(genome, config) # Start with perfect fitness, subtract error genome.fitness = 4.0 # Test on all 4 XOR cases for xi, xo in zip(xor_inputs, xor_outputs): output = net.activate(xi) genome.fitness -= (output[0] - xo[0]) ** 2 # Load configuration config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, 'config-xor') # Create population p = neat.Population(config) p.add_reporter(neat.StdOutReporter(True)) # Run evolution for up to 300 generations winner = p.run(eval_genomes, 300) # Test the winner print('\nBest genome:\n{!s}'.format(winner)) ``` -------------------------------- ### Example Parallel Reproducibility Output Source: https://github.com/codereclaimers/neat-python/blob/master/examples/parallel-reproducible/README.md Expected console output verifying that multiple runs with the same seed produce identical fitness and structural results. ```text ====================================================================== TEST 1: PARALLEL REPRODUCIBILITY (4 workers) ====================================================================== Running first parallel evolution with seed=42... Running second parallel evolution with seed=42... ====================================================================== RESULTS ====================================================================== Run 1 - Fitness: 234.50, Generations: 25, Nodes: 12, Connections: 18 Run 2 - Fitness: 234.50, Generations: 25, Nodes: 12, Connections: 18 ✓ Fitness match: True ✓ Generation match: True ✓ Structure match: True ✅ SUCCESS: Reproducibility with parallel evaluation works! ``` -------------------------------- ### NEAT Network JSON Metadata Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/network-json-format.md Provides contextual information about the exported network, including creation timestamp, NEAT-Python version, fitness, generation, and genome ID. ```json { "created_timestamp": "2025-11-09T15:23:45Z", "neat_python_version": "1.0.0", "fitness": 98.5, "generation": 42, "genome_id": 123 } ``` -------------------------------- ### GPU CTRNN Evaluator Setup Source: https://github.com/codereclaimers/neat-python/blob/master/docs/cookbook.md Use GPUCTRNNEvaluator for fast CTRNN evaluations on the GPU. Requires CuPy installation. The input_fn runs on CPU, simulation on GPU, and fitness_fn on CPU per genome. ```python import math from neat.gpu.evaluator import GPUCTRNNEvaluator def input_fn(t, dt): """Return input signal at time t. Shape: [num_inputs].""" return [math.sin(2 * math.pi * t), math.cos(2 * math.pi * t)] def fitness_fn(output_trajectory): """Compute fitness from output trajectory. Args: output_trajectory: numpy array of shape [num_steps, num_outputs] Returns: Scalar fitness value. """ # Example: reward output that tracks a target return -float(np.mean((output_trajectory[:, 0] - target) ** 2)) evaluator = GPUCTRNNEvaluator( dt=0.01, # integration timestep (seconds) t_max=1.0, # total simulation time (seconds) input_fn=input_fn, fitness_fn=fitness_fn, ) winner = population.run(evaluator.evaluate, n=300) ``` -------------------------------- ### GPU Izhikevich Network Evaluator Setup Source: https://github.com/codereclaimers/neat-python/blob/master/docs/cookbook.md Utilize GPUIZNNEvaluator for efficient Izhikevich spiking network evaluations on the GPU. Ensure CuPy is installed. input_fn operates on CPU, simulation on GPU, and fitness_fn on CPU per genome. ```python from neat.gpu.evaluator import GPUIZNNEvaluator def input_fn(t, dt): """Return input values at time t. Shape: [num_inputs].""" return [1.0, 0.5] def fitness_fn(output_trajectory): """Compute fitness from spike train. Args: output_trajectory: numpy array of shape [num_steps, num_outputs], values are 0.0 (no spike) or 1.0 (spike). """ return float(np.sum(output_trajectory)) evaluator = GPUIZNNEvaluator( dt=0.05, # integration timestep (milliseconds) t_max=50.0, # total simulation time (milliseconds) input_fn=input_fn, fitness_fn=fitness_fn, ) winner = population.run(evaluator.evaluate, n=300) ``` -------------------------------- ### Install TensorFlow Dependencies Source: https://github.com/codereclaimers/neat-python/blob/master/examples/export/README.md Install the TensorFlow library, required for TensorFlow model conversion. ```bash # For TensorFlow support pip install tensorflow ``` -------------------------------- ### NEAT Configuration File Source: https://github.com/codereclaimers/neat-python/blob/master/docs/academic_research.md A sample configuration file defining mutation rates, species settings, and stagnation parameters for NEAT-Python. ```ini # Lock to canonical activation/aggregation activation_default = sigmoid activation_mutate_rate = 0.0 activation_options = sigmoid aggregation_default = sum aggregation_mutate_rate = 0.0 aggregation_options = sum # Disable response evolution response_mutate_rate = 0.0 response_replace_rate = 0.0 # Minimal initial connectivity initial_connection = unconnected # Standard NEAT topology feed_forward = True # Canonical distance metric: no node genes, no enable penalty compatibility_include_node_genes = False compatibility_enable_penalty = 0.0 # Configure other mutation rates as needed for your problem bias_mutate_rate = 0.7 bias_replace_rate = 0.1 conn_add_prob = 0.5 conn_delete_prob = 0.5 node_add_prob = 0.2 node_delete_prob = 0.2 weight_mutate_rate = 0.8 weight_replace_rate = 0.1 [DefaultSpeciesSet] compatibility_threshold = 3.0 target_num_species = 10 [DefaultStagnation] species_fitness_func = max max_stagnation = 20 species_elitism = 2 [DefaultReproduction] elitism = 2 survival_threshold = 0.2 fitness_sharing = canonical spawn_method = proportional interspecies_crossover_prob = 0.001 ``` -------------------------------- ### Convert Network to All Formats with Output Directory Source: https://github.com/codereclaimers/neat-python/blob/master/examples/export/README.md Convert a NEAT network to all supported formats (PyTorch, TensorFlow, ONNX) and specify an output directory for the converted models. ```bash # Convert to all formats python neat_to_frameworks.py xor_winner.json --format all --output-dir ./models ``` -------------------------------- ### Install Specific Dependencies for Visualization Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Installs specific Python packages required for visualization features like graphviz, matplotlib, and network diagrams. ```bash # For visualization (XOR, pole balancing, network diagrams) pip install graphviz matplotlib ``` -------------------------------- ### Configure NEAT-Python Parameters Source: https://github.com/codereclaimers/neat-python/blob/master/docs/config_essentials.md Basic configuration settings for elitism, survival threshold, and species size. ```ini elitism = 2 # Only the top X% of each species can reproduce # 0.2 = top 20% survival_threshold = 0.2 # Minimum members for a species to be maintained min_species_size = 2 ``` -------------------------------- ### Run XOR Evolution with NEAT-Python Source: https://github.com/codereclaimers/neat-python/blob/master/docs/xor_example.md This script defines the fitness evaluation function, initializes the population, and runs the evolution process for the XOR problem. ```python """ 2-input XOR example -- this is most likely the simplest possible example. """ import os import neat import visualize # 2-input XOR inputs and expected outputs. xor_inputs = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)] xor_outputs = [(0.0,), (1.0,), (1.0,), (0.0,)] def eval_genomes(genomes, config): for genome_id, genome in genomes: genome.fitness = 4.0 net = neat.nn.FeedForwardNetwork.create(genome, config) for xi, xo in zip(xor_inputs, xor_outputs): output = net.activate(xi) genome.fitness -= (output[0] - xo[0]) ** 2 def run(config_file): # Load configuration. config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_file) # Create the population, which is the top-level object for a NEAT run. p = neat.Population(config) # Add a stdout reporter to show progress in the terminal. p.add_reporter(neat.StdOutReporter(True)) stats = neat.StatisticsReporter() p.add_reporter(stats) p.add_reporter(neat.Checkpointer(5)) # Run for up to 300 generations. winner = p.run(eval_genomes, 300) # Display the winning genome. print(f'\nBest genome:\n{winner!s}') # Show output of the most fit genome against training data. print('\nOutput:') winner_net = neat.nn.FeedForwardNetwork.create(winner, config) for xi, xo in zip(xor_inputs, xor_outputs): output = winner_net.activate(xi) print(f"input {xi!r}, expected output {xo!r}, got {output!r}") node_names = {-1: 'A', -2: 'B', 0: 'A XOR B'} visualize.draw_net(config, winner, True, node_names=node_names) visualize.draw_net(config, winner, True, node_names=node_names, prune_unused=True) visualize.plot_stats(stats, ylog=False, view=True) visualize.plot_species(stats, view=True) p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-4') p.run(eval_genomes, 10) if __name__ == '__main__': # Determine path to configuration file. This path manipulation is # here so that the script will run successfully regardless of the # current working directory. local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, 'config-feedforward') run(config_path) ``` -------------------------------- ### Interpret fitness trends Source: https://github.com/codereclaimers/neat-python/blob/master/docs/cookbook.md Examples of fitness logs representing different evolutionary states. ```text Generation 0: Best fitness = 2.1 Avg = 1.5 Generation 10: Best fitness = 3.2 Avg = 2.3 Generation 20: Best fitness = 3.7 Avg = 2.9 Generation 30: Best fitness = 3.9 Avg = 3.4 ← Converging Generation 40: Best fitness = 3.95 Avg = 3.7 ← Near threshold ``` ```text Generation 0: Best fitness = 2.1 Avg = 1.5 Generation 10: Best fitness = 2.3 Avg = 1.6 Generation 20: Best fitness = 2.4 Avg = 1.7 Generation 30: Best fitness = 2.3 Avg = 1.6 ← No improvement Generation 40: Best fitness = 2.5 Avg = 1.8 ← Stuck! ``` ```text Generation 0: Best fitness = 2.1 Avg = 1.5 Generation 10: Best fitness = 3.8 Avg = 1.9 Generation 20: Best fitness = 2.9 Avg = 1.7 ← Dropped! Generation 30: Best fitness = 3.6 Avg = 2.1 Generation 40: Best fitness = 3.0 Avg = 1.8 ← Volatile ``` -------------------------------- ### NEAT-Python Configuration for XOR Source: https://github.com/codereclaimers/neat-python/blob/master/docs/quickstart.md Configuration file for NEAT-Python to evolve a neural network for the XOR problem. Adjust parameters like population size and fitness threshold as needed. ```ini [NEAT] fitness_criterion = max fitness_threshold = 3.9 pop_size = 150 reset_on_extinction = False no_fitness_termination = False [DefaultGenome] activation_default = sigmoid activation_mutate_rate = 0.0 activation_options = sigmoid aggregation_default = sum aggregation_mutate_rate = 0.0 aggregation_options = sum bias_init_mean = 0.0 bias_init_stdev = 1.0 bias_init_type = gaussian bias_max_value = 30.0 bias_min_value = -30.0 bias_mutate_power = 0.5 bias_mutate_rate = 0.7 bias_replace_rate = 0.1 compatibility_disjoint_coefficient = 1.0 compatibility_weight_coefficient = 0.5 conn_add_prob = 0.5 conn_delete_prob = 0.5 enabled_default = True enabled_mutate_rate = 0.01 enabled_rate_to_true_add = 0.0 enabled_rate_to_false_add = 0.0 feed_forward = True initial_connection = full_direct node_add_prob = 0.2 node_delete_prob = 0.2 num_hidden = 0 num_inputs = 2 num_outputs = 1 response_init_mean = 1.0 response_init_stdev = 0.0 response_init_type = gaussian response_max_value = 30.0 response_min_value = -30.0 response_mutate_power = 0.0 response_mutate_rate = 0.0 response_replace_rate = 0.0 weight_init_mean = 0.0 weight_init_stdev = 1.0 weight_init_type = gaussian weight_max_value = 30 weight_min_value = -30 weight_mutate_power = 0.5 weight_mutate_rate = 0.8 weight_replace_rate = 0.1 single_structural_mutation = false structural_mutation_surer = default [DefaultSpeciesSet] compatibility_threshold = 3.0 [DefaultStagnation] species_fitness_func = max max_stagnation = 20 species_elitism = 2 [DefaultReproduction] elitism = 2 survival_threshold = 0.2 min_species_size = 2 ``` -------------------------------- ### Example of Extinction Error Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Sample error messages indicating that all species have gone extinct. ```text RuntimeError: All species have gone extinct ``` ```text Generation 15: Population of 0 members in 0 species Total extinctions: 3 ``` -------------------------------- ### JSON Export Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/network_export.md A sample JSON structure representing a simple XOR feedforward network. ```json { "format_version": "1.0", "network_type": "feedforward", "metadata": { "created_timestamp": "2025-11-09T15:30:00Z", "neat_python_version": "1.1.0", "fitness": 3.95, "generation": 150 }, "topology": { "num_inputs": 2, "num_outputs": 1, "input_keys": [-1, -2], "output_keys": [0] }, "nodes": [ { "id": 0, "type": "output", "activation": {"name": "sigmoid", "custom": false}, "aggregation": {"name": "sum", "custom": false}, "bias": -0.123, "response": 1.0 } ], "connections": [ {"from": -1, "to": 0, "weight": 0.75, "enabled": true} ] } ``` -------------------------------- ### Import and Use Visualize Module Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Demonstrates how to import the 'visualize' module after copying it to the project and then use its functions, such as plot_stats. ```python import visualize # Now works in your project visualize.plot_stats(stats, view=True) ``` -------------------------------- ### Identify missing fitness assignment Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Example of an incorrect implementation where the fitness value is calculated but not assigned to the genome. ```python def eval_genomes(genomes, config): for genome_id, genome in genomes: net = neat.nn.FeedForwardNetwork.create(genome, config) result = calculate_fitness(net) # Calculated but not assigned! ``` -------------------------------- ### NEAT Configuration Parameters Source: https://github.com/codereclaimers/neat-python/blob/master/docs/config_file.md Configuration settings for genome mutation and weight initialization in NEAT-Python. ```APIDOC ## Configuration Parameters ### Description These parameters define the behavior of genome mutations and weight initialization within the NEAT-Python framework. ### Parameters - **time_constant_mutate_rate** (float) - Probability that mutation changes the time constant of a node. Default: 0.0. - **time_constant_replace_rate** (float) - Probability that mutation replaces the time constant of a node. Default: 0.0. - **single_structural_mutation** (boolean) - If True, limits to one structural mutation per genome per generation. Default: False. - **structural_mutation_surer** (string/boolean) - Controls behavior for adding nodes/connections in specific edge cases. Default: "default". - **weight_init_mean** (float) - Mean of the distribution for new connection weights. - **weight_init_stdev** (float) - Standard deviation of the distribution for new connection weights. - **weight_init_type** (string) - Distribution type for weight initialization ('gaussian', 'normal', or 'uniform'). Default: "gaussian". - **weight_max_value** (float) - Maximum allowed weight value. - **weight_min_value** (float) - Minimum allowed weight value. - **weight_mutate_power** (float) - Standard deviation for weight mutation values. - **weight_mutate_rate** (float) - Probability that a weight is mutated. - **weight_replace_rate** (float) - Probability that a weight is replaced with a new random value. ``` -------------------------------- ### Custom Function Flagging Source: https://github.com/codereclaimers/neat-python/blob/master/docs/network_export.md Example showing how custom activation or aggregation functions are represented in the JSON output. ```json { "id": 0, "activation": {"name": "my_custom_activation", "custom": true} } ``` -------------------------------- ### Reset Generation Tracking Source: https://github.com/codereclaimers/neat-python/blob/master/docs/innovation_numbers.md Clears generation-specific innovation records at the start of each generation while preserving the global counter. ```python # In reproduction.py, at start of each generation: self.innovation_tracker.reset_generation() # This clears generation_innovations dict # But global_counter continues incrementing forever ``` -------------------------------- ### Convert Network to All Frameworks Source: https://github.com/codereclaimers/neat-python/blob/master/examples/export/README.md Convert an exported NEAT network JSON file to PyTorch, TensorFlow, and ONNX formats using the conversion script. ```bash python neat_to_frameworks.py xor_winner.json --format all ``` -------------------------------- ### Configure NEAT for Simple Problems Source: https://github.com/codereclaimers/neat-python/blob/master/docs/cookbook.md Sets parameters for simple problems like XOR, including a smaller population size, a clear fitness threshold, and minimal initial genome complexity. ```ini [NEAT] pop_size = 50 # Smaller population fitness_threshold = 3.9 # Clear target [DefaultGenome] num_hidden = 0 # Start minimal conn_add_prob = 0.5 node_add_prob = 0.2 ``` -------------------------------- ### Example of Stagnant Fitness Output Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md A sample log output showing a population failing to improve fitness over generations. ```text Generation 0: Best fitness: 2.1 Generation 50: Best fitness: 2.4 Generation 100: Best fitness: 2.5 ← Still stuck Generation 150: Best fitness: 2.6 ← Barely improving ``` -------------------------------- ### Implement Reproducible Parallel Evaluation Source: https://github.com/codereclaimers/neat-python/blob/master/examples/parallel-reproducible/README.md Full example showing population and evaluator initialization with a shared seed for deterministic evolution. ```python import neat def eval_genome(genome, config): # This uses Python's random module net = neat.nn.FeedForwardNetwork.create(genome, config) # ... fitness evaluation ... return fitness # Create population and evaluator with same seed config = neat.Config(...) pop = neat.Population(config, seed=42) with neat.ParallelEvaluator(4, eval_genome, seed=42) as pe: winner = pop.run(pe.evaluate, 100) ``` -------------------------------- ### Class: population.Population Source: https://github.com/codereclaimers/neat-python/blob/master/docs/module_summaries.md Initializes the core evolution algorithm for the NEAT population. ```APIDOC ## class population.Population(config, initial_state=None) ### Description Implements the core evolution algorithm by evaluating fitness, checking termination criteria, and generating new populations. ### Parameters #### Path Parameters - **config** (instance) - Required - The Config configuration object. - **initial_state** (tuple) - Optional - A tuple of (Population, Species, generation number) used for checkpoint restoration. ### Response #### Errors - **RuntimeError** - Raised if the fitness_criterion function is invalid. ``` -------------------------------- ### Correct Fitness Evaluation Patterns Source: https://github.com/codereclaimers/neat-python/blob/master/docs/cookbook.md Examples demonstrating the correct way to return fitness values and manage ParallelEvaluator resources. ```python def eval_genome(genome, config): genome.fitness = 10.0 # Don't do this! ``` ```python def eval_genome(genome, config): return 10.0 # Return the value ``` ```python evaluator = neat.ParallelEvaluator(4, eval_genome) winner = p.run(evaluator.evaluate, 300) # Pool never cleaned up! ``` ```python with neat.ParallelEvaluator(4, eval_genome) as evaluator: winner = p.run(evaluator.evaluate, 300) ``` -------------------------------- ### Enable verbose reporting and statistics Source: https://github.com/codereclaimers/neat-python/blob/master/docs/troubleshooting.md Configures standard output reporting and statistics collection for monitoring training progress. ```python # Add stdout reporter for detailed progress p.add_reporter(neat.StdOutReporter(True)) # True = verbose # Add statistics for analysis stats = neat.StatisticsReporter() p.add_reporter(stats) ``` -------------------------------- ### NEAT Configuration Parameters Source: https://github.com/codereclaimers/neat-python/blob/master/docs/config_file.md Configuration settings for managing connection mutations and initial genome topology. ```APIDOC ## Configuration Parameters ### Description Settings for controlling the mutation behavior of connections and the initial structure of genomes in the NEAT-Python library. ### Parameters - **enabled_mutate_rate** (float) - Probability [0.0, 1.0] that mutation will replace the enabled status of a connection. - **enabled_rate_to_false_add** (float) - Value added to enabled_mutate_rate if the connection is currently enabled. - **enabled_rate_to_true_add** (float) - Value added to enabled_mutate_rate if the connection is currently disabled. - **feed_forward** (boolean) - If True, generated networks are restricted to feedforward architectures. - **initial_connection** (string) - Specifies the initial connectivity strategy for new genomes. Valid values: 'unconnected', 'fs_neat_nohidden', 'fs_neat_hidden', 'full_nodirect', 'full_direct', 'partial_nodirect #', 'partial_direct #'. ``` -------------------------------- ### NEAT Network JSON Connection Example Source: https://github.com/codereclaimers/neat-python/blob/master/docs/network-json-format.md Defines a weighted connection between two nodes in the network, specifying the source, destination, weight, and enabled status. ```json { "from": -1, "to": 0, "weight": 0.75, "enabled": true } ``` -------------------------------- ### Configure Activation Functions in NEAT-Python Source: https://github.com/codereclaimers/neat-python/blob/master/docs/cookbook.md Set activation functions via the configuration file to control output ranges or allow mutation between multiple options. ```ini [DefaultGenome] # For outputs in range [-1, 1] activation_default = tanh activation_mutate_rate = 0.0 # Don't change activation activation_options = tanh # Only allow tanh ``` ```ini # Allow multiple options, set mutation rate > 0 activation_default = tanh activation_mutate_rate = 0.2 activation_options = tanh sigmoid relu ```