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 |
// Save a genome to JSON
const 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 |
// Load a genome from JSON string
const 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
// After evolution completes, get the best genome
const bestGenome = population.getBestGenome();
// Save the best genome to JSON
const jsonString = bestGenome.toJSON();
console.log("Best genome saved, fitness:", bestGenome.fitness);
// Store in a file
const fs = require('fs');
fs.writeFileSync('best_genome.json', jsonString);
// Later, in another session, load the genome back
const savedGenomeJson = fs.readFileSync('best_genome.json', 'utf8');
const loadedGenome = GenomeBuilder.loadGenome(savedGenomeJson, config);
// Use the loaded genome for inference
const inputs = [0.5, 0.7];
loadedGenome.resetState();
const outputs = loadedGenome.propagate(inputs);
console.log("Loaded genome outputs:", outputs);