npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@leoni4/neat-js

v1.3.1

Published

NEAT Neural Network Implementation in TypeScript

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-js

Usage

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 logic

Constructor

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 change Math.random. Each Neat instance 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)), also 0 and negative values. 0 and -0 give the same sequence. Other values (for example 1.5, NaN, Infinity, 2 ** 53, or a string) make the constructor throw seed must be a safe integer (got …).
  • Without seed (or with seed: undefined or null), the library uses Math.random(), as before. It reads Math.random at each draw.
  • The same seed gives the same mutations, innovation IDs, crossover, species, selection, and evolution history (evolve() and fit()). 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.score and client.error values);
    • the same JavaScript runtime. Identical results on other engines or engine versions are not verified: scores and activations use Math.exp, Math.tanh, and Math.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, and counter are 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, algorithm must be 'sfc32', and each of a, b, c, and counter must 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.rng stays the same function. A reference to neat.rng that you took before restoreRandomState() 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 at randomState().
  • 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.score for each client before each neat.evolve() call. A higher score is better.
  • The score can be any finite number (also negative). evolve() throws an error when a score is NaN, Infinity, or -Infinity.
  • evolve() changes client.score. It adds a small random tie-breaker (neat.rng() * 1e-9; the seeded generator with seed, Math.random() without seed) and stores the result in client.scoreRaw. Then it replaces client.score with a normalized score in [0, 1] that includes a complexity penalty. Do not read client.score after evolve() 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.error to your error measure, where 0 is perfect (for example, the mean absolute error), as in the manual example above.
  • If your task has no error measure, set client.error to a value that is not smaller than OPT_ERR_THRESHOLD (for example 1) while you want the networks to grow, or set the param ERROR_DRIVES_OPTIMIZATION: false: then client.error never turns on self-optimization (see ERROR_DRIVES_OPTIMIZATION).
  • neat.fit() sets both client.error and client.score for 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; with CHAMPION_MAX_AGE, one champion is kept for not more than that number of generations, see CHAMPION_MAX_AGE). Before the first evolve(), 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 (default 0.5) is the fraction of clients that get their own copy of the loaded genome. The other clients start with empty genomes. LOAD_PERCENT: 0 loads no client.
  • evolveCounts continues the generation counter. If it is missing, null, or NaN, the constructor prints a warning and uses 0. With 0, the first evolve() call mutates all clients, also the best one (the same as for a new population). With a value that is not 0, 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 start

The 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 demo
  • npm run build - Build the library for production
  • npm run build:demo - Build the demo for production
  • npm test - Run tests
  • npm run test:watch - Run tests in watch mode
  • npm run lint - Lint the codebase
  • npm run typecheck - Run TypeScript type checking
  • npm run bench - Run the RandomHashSet micro-benchmark against the 1.3.0 algorithm (not part of npm test)

API

Core Classes

  • Neat - Main NEAT algorithm class
  • Client - Individual neural network in the population
  • Genome - Genetic representation of a neural network
  • Species - Group of similar genomes

Data Structures

  • RandomHashSet - Efficient random selection from a set
  • RandomSelector - 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

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes with tests
  4. Ensure all tests pass: npm test
  5. Submit a pull request

License

MIT

Repository

https://github.com/leoni4/neat-js