@leoni4/neat-js
v1.3.1
Published
NEAT Neural Network Implementation in TypeScript
Maintainers
Readme
🧬 NEAT.js
A TypeScript implementation of the NEAT (NeuroEvolution of Augmenting Topologies) algorithm for evolving neural networks.
🎮 Live Demo
Try the interactive demo: https://leoni4.github.io/neat-js/
The demo showcases NEAT solving various problems including XOR, parity functions, and classification tasks with real-time visualization of the neural network evolution.
Installation
npm install @leoni4/neat-jsUsage
Basic Library Usage
import { Neat } from '@leoni4/neat-js';
// Create a NEAT instance
const neat = new Neat(
2, // input nodes
1, // output nodes
1000, // population size
);
// Training data (XOR example)
const inputs = [
[0, 0],
[1, 1],
[1, 0],
[0, 1],
];
const outputs = [[0], [0], [1], [1]];
const solved = neat.fit(inputs, outputs, {
verbose: 1,
});
console.log('solved in:', solved.epochs);Manual Library Usage
Could be helpfull with non linear score determination, or complex environment
import { Neat } from '@leoni4/neat-js';
// Create a NEAT instance same as above
const neat = new Neat(2, 1, 1000);
// Training data (XOR example) ... same as above
const inputs = [
[0, 0],
[1, 1],
[1, 0],
[0, 1],
];
const outputs = [[0], [0], [1], [1]];
let finalError = 1; // just for the demo
let counter = 0;
// Evolution loop
for (let epoch = 0; epoch < 1000; epoch++) {
// Evaluate each client
for (const client of neat.clients) {
let error = 0;
inputs.forEach((input, i) => {
const output = client.calculate(input)[0];
error += Math.abs(output - outputs[i][0]);
});
error = error / inputs.length;
// calculate error and score of the client
client.error = error;
client.score = 1 - client.error;
if (finalError > error) {
finalError = error;
}
}
counter++;
// Evolve to next generation
neat.evolve();
if (epoch % 10 === 0) console.log('Epoch:', epoch, ' Error:', finalError);
if (finalError < 0.01) break;
}
console.log('Total epochs:', counter, ' Final Error:', finalError);
// ... rest of the logicConstructor
import { Neat, EActivation } from '@leoni4/neat-js';
const neat = new Neat(
2, // input nodes
1, // output nodes
100, // population size
EActivation.sigmoid, // output activation (default: sigmoid)
EActivation.tanh, // hidden activation (default: tanh)
{ CP: 2, PROBABILITY_MUTATE_LINK: 0.1 }, // parameters (optional)
// 7th argument: { genome, evolveCounts } to load a saved model (optional)
);The parameters are the 6th argument. Pass both activations before them. All parameters, their defaults, and tuning tips are in docs/PARAMETER_TUNING.md.
Activations (EActivation): none, linear, sigmoid, tanh, relu, leakyRelu, softmax. As the output activation, softmax normalizes all outputs together. As the hidden activation, softmax acts as linear.
Reproducible runs (seed)
Set the seed param to make a run reproducible:
import { Neat, EActivation } from '@leoni4/neat-js';
const neat = new Neat(12, 2, 100, EActivation.sigmoid, EActivation.tanh, {
seed: 12345,
});- With
seed, the instance uses its own seeded generator, sfc32 ("Small Fast Counting" RNG v4 from PractRand), for all random draws. It does not read or changeMath.random. EachNeatinstance has its own generator state, so two instances with the same seed do not affect each other. - The seed can be any safe integer (
Number.isSafeInteger(seed)), also0and negative values.0and-0give the same sequence. Other values (for example1.5,NaN,Infinity,2 ** 53, or a string) make the constructor throwseed must be a safe integer (got …). - Without
seed(or withseed: undefinedornull), the library usesMath.random(), as before. It readsMath.randomat each draw. - The same seed gives the same mutations, innovation IDs, crossover, species, selection, and evolution history (
evolve()andfit()). This is true only with all of these:- the same seed;
- the same configuration (all constructor arguments and params, also the loaded model);
- the same library version;
- the same sequence of operations (the same calls in the same order, with the same
client.scoreandclient.errorvalues); - the same JavaScript runtime. Identical results on other engines or engine versions are not verified: scores and activations use
Math.exp,Math.tanh, andMath.log1p, and the last bit of these results can be different between engines.
- Your fitness code must also be deterministic. If it uses
Math.random, the time, or the order of async operations, the scores change and the run is not reproducible. model()does not save the seed or the generator state. A model that you load with a seed starts the random stream again from the beginning. It does not continue the random stream of the original run. To save and set the position of the random stream, see Save and restore the random stream.
Save and restore the random stream
An instance with seed can give the position of its random stream as plain JSON data. Another instance with seed (the seed value can be different) can continue the stream from that position:
import { Neat, EActivation, type NeatRandomState } from '@leoni4/neat-js';
const neat = new Neat(2, 1, 100, EActivation.sigmoid, EActivation.tanh, { seed: 12345 });
// ... evolve, or make and mutate clients ...
// Save
const state: NeatRandomState = neat.randomState();
const json = JSON.stringify(state);
// Restore
const restored = new Neat(2, 1, 100, EActivation.sigmoid, EActivation.tanh, { seed: 12345 });
restored.restoreRandomState(JSON.parse(json));
// The next draws of `restored` are the draws that came after randomState() in `neat`.randomState()returns a new object{ algorithm: 'sfc32', a, b, c, counter }.a,b,c, andcounterare integers in [0, 2^32 − 1]. The call takes no draw and does not change the stream.restoreRandomState(state)checks the state first: it must be a plain object,algorithmmust be'sfc32', and each ofa,b,c, andcountermust be an integer in [0, 2^32 − 1]. For an invalid state, it throws an error that names the field, and the instance keeps its current state.- Without
seed, both methods throw an error. neat.rngstays the same function. A reference toneat.rngthat you took beforerestoreRandomState()continues from the restored state.- The two methods save and set the random stream only. They do not save or set the clients, the genomes, the species, the champion, the innovation IDs, or
evolveCounts. The next results are the same as in the original run only when all of this other state is also the same as atrandomState(). - A restored stream gives the same results only with the same library version, the same configuration, and the same sequence of operations.
Score rules
- Set
client.scorefor each client before eachneat.evolve()call. A higher score is better. - The score can be any finite number (also negative).
evolve()throws an error when a score isNaN,Infinity, or-Infinity. evolve()changesclient.score. It adds a small random tie-breaker (neat.rng() * 1e-9; the seeded generator withseed,Math.random()withoutseed) and stores the result inclient.scoreRaw. Then it replacesclient.scorewith a normalized score in [0, 1] that includes a complexity penalty. Do not readclient.scoreafterevolve()as your own value.neat.evolve()takes one optional argument:evolve(true)turns on the global optimization mode for this call.
Set client.error and client.score
client.error is not only for logging. evolve() compares client.error with OPT_ERR_THRESHOLD (default 0.005) before it mutates a client. When client.error < OPT_ERR_THRESHOLD, the client is in self-optimization mode: it removes disabled and dead connections, and it does not add new connections or nodes.
The default value of client.error is 0. If you set only client.score, all clients are in self-optimization mode from the second evolve() call, and the networks stop growing after the first connection.
- Set
client.errorto your error measure, where0is perfect (for example, the mean absolute error), as in the manual example above. - If your task has no error measure, set
client.errorto a value that is not smaller thanOPT_ERR_THRESHOLD(for example1) while you want the networks to grow, or set the paramERROR_DRIVES_OPTIMIZATION: false: thenclient.errornever turns on self-optimization (see ERROR_DRIVES_OPTIMIZATION). neat.fit()sets bothclient.errorandclient.scorefor you.
Save and load a model
import { Neat, EActivation } from '@leoni4/neat-js';
const neat = new Neat(2, 1, 100, EActivation.sigmoid, EActivation.tanh);
// ... set scores and call neat.evolve() ...
// Save
const saved = { genome: neat.model(), evolveCounts: neat.evolveCounts };
const json = JSON.stringify(saved);
// Load: use the same inputs, outputs, and activations
const restored = new Neat(2, 1, 100, EActivation.sigmoid, EActivation.tanh, { LOAD_PERCENT: 0.5 }, JSON.parse(json));neat.model()returns the genome of the champion (a copy of the client with the highest raw score of all generations so far; withCHAMPION_MAX_AGE, one champion is kept for not more than that number of generations, see CHAMPION_MAX_AGE). Before the firstevolve(), it returns the genome of the best or first client.- The model contains the genome only. It does not contain the number of inputs and outputs, the activations, or the parameters. Use the same values when you load it.
LOAD_PERCENT(default0.5) is the fraction of clients that get their own copy of the loaded genome. The other clients start with empty genomes.LOAD_PERCENT: 0loads no client.evolveCountscontinues the generation counter. If it is missing,null, orNaN, the constructor prints a warning and uses0. With0, the firstevolve()call mutates all clients, also the best one (the same as for a new population). With a value that is not0, the best client is not mutated. The counter also sets when the next global optimization phase comes (evolveCounts % OPTIMIZATION_PERIOD === 0).
Frozen model. To use a saved model for predictions only, load it into a population of 1 and call neat.calculate(). It uses the champion, or the first client when there is no champion:
const frozen = new Neat(2, 1, 1, EActivation.sigmoid, EActivation.tanh, {}, JSON.parse(json));
const output = frozen.calculate([0, 1]);A population of 1 does not change after the first evolve() call: the only client is always the best client, and the best client is not mutated. Use a population of 1 only for frozen models.
Development
Running the Demo
Clone the repository and run the demo locally:
git clone https://github.com/leoni4/neat-js.git
cd neat-js
npm install
npm startThe demo will start a Vite development server at http://localhost:3000 with a visual demonstration of the NEAT algorithm solving the selected problem.
Available Scripts
npm start- Start the Vite development server with demonpm run build- Build the library for productionnpm run build:demo- Build the demo for productionnpm test- Run testsnpm run test:watch- Run tests in watch modenpm run lint- Lint the codebasenpm run typecheck- Run TypeScript type checkingnpm run bench- Run theRandomHashSetmicro-benchmark against the 1.3.0 algorithm (not part ofnpm test)
API
Core Classes
Neat- Main NEAT algorithm classClient- Individual neural network in the populationGenome- Genetic representation of a neural networkSpecies- Group of similar genomes
Data Structures
RandomHashSet- Efficient random selection from a setRandomSelector- Weighted random selection
RandomHashSet.randomElement(rng?) and RandomSelector.random(rng?) take an optional random function that returns values in [0, 1). The default is Math.random(). Neat gives them its rng.
Complexity of RandomHashSet with n genes (since 1.3.1, the set keeps a Map from innovation number to gene next to its array):
| Method | Cost |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| contains(), add() | O(1) |
| addSorted() | O(1) when the innovation number is not lower than any innovation number added since the last clear() (an append). Other inserts scan for the position: O(n). |
| remove(), removeByInnovation() | O(n) |
Thus a set of n genes from add(), or from addSorted() in ascending order (for example when a saved genome is loaded), takes O(n) to build. In 1.3.0 it took O(n²). The gene order and all results are the same as in 1.3.0.
RandomHashSet.data returns the internal array. Treat it as read-only, and change a set only with add(), addSorted(), remove(), removeByInnovation(), and clear(). A direct change of the array (for example set.data.push(gene)) bypasses the index, and then contains() and addSorted() can give wrong results.
Internal methods
These Neat methods are public in TypeScript, but they are internal. Do not call them from your code: load(), loadGenome(), reset(), getConnection(), getNode(), setReplaceIndex(), getReplaceIndex(), emptyGenome(), and the static Neat.getConnection(). For example, load() on an instance that already has clients adds a second set of clients. To load a model, use the 7th constructor argument (see Save and load a model).
The neat.rng getter is also internal. It returns the random function of the instance (the seeded generator, or Math.random() without seed). Each call takes one draw from the stream and changes all later draws. Do not call it in your code when you need reproducible results.
Contributing
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Ensure all tests pass:
npm test - Submit a pull request
License
MIT
Repository
https://github.com/leoni4/neat-js
