or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cross-validation.mdindex.mdneural-networks.mdrecurrent-networks.mdutilities.md
tile.json

utilities.mddocs/

Utilities

Data processing utilities, lookup tables, mathematical functions, and streaming capabilities for neural network operations. These utilities support data preparation, result interpretation, and advanced training workflows.

Capabilities

Helper Functions

likely Function

Finds the most likely output classification from neural network results.

/**
 * Find the most likely output property from network results
 * @param input - Input data to run through the network
 * @param network - Trained neural network instance
 * @returns The property key with the highest probability value
 */
function likely(input: any, network: NeuralNetwork): string;

Usage Examples:

const brain = require('brain.js');

// Train a classification network
const net = new brain.NeuralNetwork();
net.train([
  { input: { r: 0.03, g: 0.7, b: 0.5 }, output: { black: 1 } },
  { input: { r: 0.16, g: 0.09, b: 0.2 }, output: { white: 1 } },
  { input: { r: 0.5, g: 0.5, b: 1.0 }, output: { white: 1 } }
]);

// Get most likely classification
const color = brain.likely({ r: 1, g: 0.4, b: 0 }, net);
console.log(color); // 'white' or 'black'

// Compare with raw output
const rawOutput = net.run({ r: 1, g: 0.4, b: 0 });
console.log(rawOutput); // { black: 0.123, white: 0.987 }
console.log(brain.likely({ r: 1, g: 0.4, b: 0 }, net)); // 'white'

Lookup Tables

lookup Class

Utility class for converting between sparse hash objects and dense arrays, essential for handling categorical data in neural networks.

/**
 * Utility class for converting between hashes and arrays
 * Static methods for data transformation operations
 */
class lookup {
  /**
   * Build lookup table from array of hash objects
   * @param hashes - Array of objects with different keys
   * @returns Lookup object mapping keys to indices
   */
  static buildLookup(hashes: object[]): object;
  
  /**
   * Create lookup table from a single hash object
   * @param hash - Object with key-value pairs
   * @returns Lookup object mapping keys to indices
   */
  static lookupFromHash(hash: object): object;
  
  /**
   * Convert hash to array using lookup table
   * @param lookup - Lookup table mapping keys to indices
   * @param hash - Hash object to convert
   * @returns Dense array representation
   */
  static toArray(lookup: object, hash: object): number[];
  
  /**
   * Convert array to hash using lookup table
   * @param lookup - Lookup table mapping keys to indices
   * @param array - Dense array to convert
   * @returns Hash object representation
   */
  static toHash(lookup: object, array: number[]): object;
  
  /**
   * Create lookup table from array values
   * @param array - Array of values to create lookup from
   * @returns Lookup object mapping values to indices
   */
  static lookupFromArray(array: any[]): object;
}

Usage Examples:

const brain = require('brain.js');

// Build lookup from multiple objects
const data = [
  { sunny: 1, cloudy: 0, rainy: 0 },
  { sunny: 0, cloudy: 1, rainy: 0 },
  { sunny: 0, cloudy: 0, rainy: 1 }
];

const weatherLookup = brain.lookup.buildLookup(data);
console.log(weatherLookup); // { sunny: 0, cloudy: 1, rainy: 2 }

// Convert hash to array
const todayWeather = { sunny: 1, cloudy: 0, rainy: 0 };
const weatherArray = brain.lookup.toArray(weatherLookup, todayWeather);
console.log(weatherArray); // [1, 0, 0]

// Convert array back to hash
const backToHash = brain.lookup.toHash(weatherLookup, weatherArray);
console.log(backToHash); // { sunny: 1, cloudy: 0, rainy: 0 }

// Create lookup from single hash
const colors = { red: 0.8, green: 0.2, blue: 0.1 };
const colorLookup = brain.lookup.lookupFromHash(colors);
console.log(colorLookup); // { red: 0, green: 1, blue: 2 }

// Create lookup from array
const fruits = ['apple', 'banana', 'orange'];
const fruitLookup = brain.lookup.lookupFromArray(fruits);
console.log(fruitLookup); // { orange: 0, banana: 1, apple: 2 }

Stream Processing

TrainStream Class

Streaming interface for training neural networks with large datasets that don't fit in memory.

/**
 * Stream-based training for neural networks
 * Extends Node.js Writable stream for handling large datasets
 */
class TrainStream extends require('stream').Writable {
  /**
   * Create a training stream
   * @param options - Stream configuration options
   */
  constructor(options: {
    /** Neural network instance to train */
    neuralNetwork: NeuralNetwork;
    /** Callback when stream buffer is full */
    floodCallback?: () => void;
    /** Callback when training is complete */
    doneTrainingCallback?: (stats: TrainingStats) => void;
    /** Maximum training iterations (default: 20000) */
    iterations?: number;
    /** Error threshold for stopping (default: 0.005) */
    errorThresh?: number;
    /** Enable logging or provide custom log function */
    log?: boolean | ((stats: TrainingStats) => void);
    /** Iterations between log outputs (default: 10) */
    logPeriod?: number;
    /** Periodic callback during training */
    callback?: (stats: TrainingStats) => void;
    /** Iterations between callback calls (default: 10) */
    callbackPeriod?: number;
  });
  
  /**
   * Write training data to the stream
   * @param data - Training data object
   */
  write(data: { input: any; output: any }): void;
  
  /**
   * Signal end of input data and start training
   */
  endInputs(): void;
}

interface TrainingStats {
  iterations: number;
  error: number;
}

Usage Examples:

const brain = require('brain.js');
const fs = require('fs');

// Create network and training stream
const net = new brain.NeuralNetwork();
const trainStream = new brain.TrainStream({
  neuralNetwork: net,
  doneTrainingCallback: (stats) => {
    console.log(`Training completed: ${stats.iterations} iterations, error: ${stats.error}`);
  },
  floodCallback: () => {
    console.log('Stream buffer full, processing batch...');
  }
});

// Stream training data
trainStream.write({ input: [0, 0], output: [0] });
trainStream.write({ input: [0, 1], output: [1] });
trainStream.write({ input: [1, 0], output: [1] });
trainStream.write({ input: [1, 1], output: [0] });

// End training
trainStream.endInputs();

// Stream from file
const dataStream = fs.createReadStream('training-data.json');
dataStream.pipe(trainStream);

Mathematical Utilities

The utilities namespace provides various mathematical and data manipulation functions.

/**
 * Collection of utility functions for neural network operations
 */
const utilities: {
  /** Find maximum value in array */
  max: (array: number[]) => number;
  
  /** Calculate mean squared error */
  mse: (actual: number[], predicted: number[]) => number;
  
  /** Create array filled with ones */
  ones: (size: number) => number[];
  
  /** Generate random number */
  random: () => number;
  
  /** Generate random weight value */
  randomWeight: () => number;
  
  /** Generate array of random values */
  randos: (size: number) => number[];
  
  /** Create range of numbers */
  range: (start: number, end?: number) => number[];
  
  /** Convert value to array */
  toArray: (value: any) => any[];
  
  /** Create array filled with zeros */
  zeros: (size: number) => number[];
  
  /** Data formatting utility class */
  DataFormatter: typeof DataFormatter;
};

max Function

/**
 * Find the maximum value in an array
 * @param array - Array of numbers
 * @returns Maximum value
 */
function max(array: number[]): number;

mse Function

/**
 * Calculate mean squared error between actual and predicted values
 * @param actual - Array of actual values
 * @param predicted - Array of predicted values
 * @returns Mean squared error
 */
function mse(actual: number[], predicted: number[]): number;

Array Generation Functions

/**
 * Create array filled with ones
 * @param size - Array size
 * @returns Array of ones
 */
function ones(size: number): number[];

/**
 * Create array filled with zeros
 * @param size - Array size
 * @returns Array of zeros
 */
function zeros(size: number): number[];

/**
 * Generate array of random values
 * @param size - Array size
 * @returns Array of random numbers
 */
function randos(size: number): number[];

/**
 * Create range of numbers
 * @param start - Starting number
 * @param end - Ending number (optional)
 * @returns Array of sequential numbers
 */
function range(start: number, end?: number): number[];

Random Functions

/**
 * Generate random number between 0 and 1
 * @returns Random number
 */
function random(): number;

/**
 * Generate random weight value (typically between -1 and 1)
 * @returns Random weight
 */
function randomWeight(): number;

Usage Examples:

const brain = require('brain.js');

// Mathematical operations
const numbers = [1, 5, 3, 9, 2];
const maxValue = brain.utilities.max(numbers);
console.log(maxValue); // 9

const actual = [1, 2, 3];
const predicted = [1.1, 2.2, 2.8];
const error = brain.utilities.mse(actual, predicted);
Console.log(error); // 0.05

// Array generation
const onesArray = brain.utilities.ones(5);
console.log(onesArray); // [1, 1, 1, 1, 1]

const zerosArray = brain.utilities.zeros(3);
console.log(zerosArray); // [0, 0, 0]

const randomArray = brain.utilities.randos(4);
console.log(randomArray); // [0.123, 0.456, 0.789, 0.321]

const sequence = brain.utilities.range(1, 5);
console.log(sequence); // [1, 2, 3, 4]

// Random values
const randomNum = brain.utilities.random();
const randomWt = brain.utilities.randomWeight();

Data Formatting

DataFormatter Class

Advanced data formatting utility for preparing complex data structures for neural network training.

/**
 * Data formatter for preparing training data
 * Handles character sequences, numerical data, and mixed types
 */
class DataFormatter {
  /**
   * Create data formatter
   * @param values - Input values to analyze and format
   * @param maxThreshold - Maximum threshold for character filtering
   */
  constructor(values?: string[] | number[], maxThreshold?: number);
  
  /** Mapping from characters/values to indices */
  indexTable: { [key: string]: number };
  
  /** Reverse mapping from indices to characters/values */
  characterTable: { [key: number]: string };
  
  /** Array of unique characters/values found in data */
  characters: any[];
  
  /** Array of special index positions */
  specialIndexes: number[];
  
  /**
   * Build character set from iterable data
   * @param values - Data to analyze for characters
   */
  buildCharactersFromIterable(values: any[]): void;
  
  /**
   * Build lookup tables with threshold filtering
   * @param maxThreshold - Filter characters above this threshold
   */
  buildTables(maxThreshold: number): void;
}

Usage Examples:

const brain = require('brain.js');

// Format text data for RNN training
const textData = [
  'hello world',
  'goodbye world',
  'hello universe'
];

const formatter = new brain.utilities.DataFormatter(textData);

console.log('Characters found:', formatter.characters);
// ['h', 'e', 'l', 'o', ' ', 'w', 'r', 'd', 'g', 'b', 'y', 'u', 'n', 'i', 'v', 's']

console.log('Index mapping:', formatter.indexTable);
// { 'h': 0, 'e': 1, 'l': 2, 'o': 3, ' ': 4, 'w': 5, ... }

console.log('Character mapping:', formatter.characterTable);
// { 0: 'h', 1: 'e', 2: 'l', 3: 'o', 4: ' ', 5: 'w', ... }

// Use with RNN
const rnn = new brain.recurrent.LSTM();
rnn.dataFormatter = formatter;
rnn.train(textData);

// Format numerical sequences
const numberSequences = [
  [1, 2, 3, 4, 5],
  [2, 3, 4, 5, 6],
  [3, 4, 5, 6, 7]
];

const numFormatter = new brain.utilities.DataFormatter(numberSequences.flat());
console.log('Unique numbers:', numFormatter.characters);

Conversion Utilities

toArray Function

/**
 * Convert various data types to array format
 * @param value - Value to convert to array
 * @returns Array representation
 */
function toArray(value: any): any[];

Usage Examples:

// Convert different types to arrays
const string = 'hello';
const stringArray = brain.utilities.toArray(string);
console.log(stringArray); // ['h', 'e', 'l', 'l', 'o']

const number = 12345;
const numberArray = brain.utilities.toArray(number);
console.log(numberArray); // ['1', '2', '3', '4', '5']

const object = { a: 1, b: 2, c: 3 };
const objectArray = brain.utilities.toArray(object);
console.log(objectArray); // [1, 2, 3]

Complete Utility Usage Example

const brain = require('brain.js');

// Prepare categorical data using lookup utilities
const rawData = [
  { weather: 'sunny', temp: 'hot', play: 'yes' },
  { weather: 'cloudy', temp: 'mild', play: 'yes' },
  { weather: 'rainy', temp: 'cool', play: 'no' }
];

// Create lookups for categorical variables
const weatherLookup = brain.lookup.buildLookup(rawData.map(d => ({ [d.weather]: 1 })));
const tempLookup = brain.lookup.buildLookup(rawData.map(d => ({ [d.temp]: 1 })));
const playLookup = brain.lookup.buildLookup(rawData.map(d => ({ [d.play]: 1 })));

// Convert to training format
const trainingData = rawData.map(item => ({
  input: [
    ...brain.lookup.toArray(weatherLookup, { [item.weather]: 1 }),
    ...brain.lookup.toArray(tempLookup, { [item.temp]: 1 })
  ],
  output: brain.lookup.toArray(playLookup, { [item.play]: 1 })
}));

// Train network
const net = new brain.NeuralNetwork();
net.train(trainingData);

// Make prediction
const testInput = [
  ...brain.lookup.toArray(weatherLookup, { sunny: 1 }),
  ...brain.lookup.toArray(tempLookup, { mild: 1 })
];

const rawOutput = net.run(testInput);
const predictedPlay = brain.lookup.toHash(playLookup, rawOutput);
const mostLikely = brain.likely(predictedPlay, net);

console.log('Prediction:', mostLikely);