Genome Serialization
The NEAT library provides functionality to save genomes to JSON format and load them back, allowing for persistence of evolved neural networks across sessions.
Saving Genomes
toJSON
genome.toJSON() → String
Converts a genome to a JSON string representation that can be stored in a file or database.
| Returns | Type | Description |
|---|---|---|
| jsonString | String | JSON string representation of the genome |
javascript
// Save a genome to JSONconst jsonString = genome.toJSON();console.log(jsonString);
// Write to a file (in Node.js)const fs = require('fs');fs.writeFileSync('best_genome.json', jsonString);Note
The JSON structure includes the genome's ID, node genes, connection genes, fitness score, and population ID. This provides all the information needed to reconstruct the genome later.
Loading Genomes
GenomeBuilder.loadGenome
GenomeBuilder.loadGenome(jsonData, config) → Genome
Recreates a genome from its JSON representation.
| Parameter | Type | Description |
|---|---|---|
| jsonData | String | JSON string representation of a genome |
| config | Object | Configuration parameters for the genome |
| Returns | Type | Description |
|---|---|---|
| genome | Genome | A reconstructed genome with the same structure and weights |
javascript
// Load a genome from JSON stringconst jsonString = genome.toJSON();const newGenome = GenomeBuilder.loadGenome(jsonString, config);
// Load from a file (in Node.js)const fs = require('fs');const savedGenomeJson = fs.readFileSync('best_genome.json', 'utf8');const loadedGenome = GenomeBuilder.loadGenome(savedGenomeJson, config);Example: Saving and Loading the Best Genome
javascript
// After evolution completes, get the best genomeconst bestGenome = population.getBestGenome();
// Save the best genome to JSONconst jsonString = bestGenome.toJSON();console.log("Best genome saved, fitness:", bestGenome.fitness);
// Store in a fileconst fs = require('fs');fs.writeFileSync('best_genome.json', jsonString);
// Later, in another session, load the genome backconst savedGenomeJson = fs.readFileSync('best_genome.json', 'utf8');const loadedGenome = GenomeBuilder.loadGenome(savedGenomeJson, config);
// Use the loaded genome for inferenceconst inputs = [0.5, 0.7];loadedGenome.resetState();const outputs = loadedGenome.propagate(inputs);console.log("Loaded genome outputs:", outputs);