@ekatomp4/nural
v1.0.1
Published
An easily adaptable library for building highly customizable neural networks.
Readme
Nural
An easily adaptable Node.js (ESM) library for building and training small neural networks on top of TensorFlow.js.
This folder (Nural/) is the actual npm package: @ekatomp4/nural.
Install
From npm (recommended for consumers)
npm i @ekatomp4/nuralFrom this repo (local development)
cd "Nural"
npm iQuick start
import Nural, { Layer } from "@ekatomp4/nural";
const model = new Nural({
inputShape: [2],
layers: [
new Layer({ units: 8, activation: "relu" }),
new Layer({ units: 1, activation: "sigmoid" }),
],
optimizationLevel: 3,
});
await model.train(
[
{ input: [0, 0], output: [0] },
{ input: [0, 1], output: [1] },
{ input: [1, 0], output: [1] },
{ input: [1, 1], output: [0] },
],
{ epochs: 50, batchSize: 4 }
);
console.log(model.predict([0, 1])[0]);Concepts
Nural
Default export. Wraps a tf.Sequential model, wires up layers, compiles, trains, and predicts.
Constructor:
new Nural({
layers, // Layer[] (required unless you load a model yourself)
inputShape, // number[] (required for first layer)
optimizationLevel, // 1|2|3, enables early-stopping logic in training (default: 3)
optimizer, // passed to tf.Model.compile (default: "adam")
loss, // passed to tf.Model.compile (default: "binaryCrossentropy")
metrics, // passed to tf.Model.compile (default: ["accuracy"])
path, // (see note below)
})Important note about path:
tf.loadLayersModel(...)is async; the current code assigns the returned Promise tothis.model. If you need loading today, load the model yourself and/or adjust the implementation before usingtrain()/predict().
Layer
Named export, and also available as Nural.Layer.
import Nural, { Layer } from "@ekatomp4/nural";
// or: const Layer = Nural.Layer;By default, Layer builds a TensorFlow.js layer via tf.layers[this.type](...) (default type: "dense").
Create a dense layer:
new Layer({ units: 32, activation: "relu" })Custom layers
You can build a custom tf.layers.Layer via constructCustomLayer(...):
const custom = new Layer({ units: 8 }).constructCustomLayer({
className: "MyCustomLayer",
build(inputShape) {
this.kernel = this.addWeight(
"kernel",
[inputShape[1], this.units],
"float32",
tf.initializers.glorotNormal()
);
this.bias = this.addWeight("bias", [this.units], "float32", tf.initializers.zeros());
},
call(x) {
return tf.tanh(tf.add(tf.matMul(x, this.kernel.read()), this.bias.read()));
},
});Then include it in layers: [custom, ...].
Data format
Training (train)
train(data, options) expects an array of samples:
{ input: any[]; output: any[] }The current implementation checks that sample.input is an array and that sample.input.length matches the model’s expected input size.
Inputs/outputs are normalized before training:
numberstays numericbooleanbecomes0/1stringbecomes:- a number (if it parses as a numeric string), otherwise
- a list of character codes divided by
255
- arrays are recursively flattened
Tip: if you pass strings, keep them a fixed shape that matches your inputShape (for example: single characters if inputShape: [1]).
Training options:
await model.train(data, {
epochs: 10,
batchSize: 32,
callbacks: [], // additional tfjs callbacks
});Prediction (predict)
predict(input) normalizes the input, converts it to a 2D tensor with batch dimension 1, and returns the raw numeric output(s):
const out = model.predict([1, 0]); // returns a TypedArray (via dataSync())Scripts
From Nural/:
npm run startrunsnode index.js(this package is a library;index.jsmainly exports symbols)npm testis currently a placeholder
Environment variables
None required.
Node + TensorFlow.js notes
This package depends on @tensorflow/tfjs. For better performance in Node, you can optionally install a native backend (for example @tensorflow/tfjs-node) in your consuming app and import it once at startup so TensorFlow.js uses it.
