Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,20 @@ <h1 class="l--page">Tinker With a <b>Neural Network</b> <span class="optional">R
<option value="tanh">Tanh</option>
<option value="sigmoid">Sigmoid</option>
<option value="linear">Linear</option>
<option value="leakyRelu">Leaky ReLU</option>
<option value="elu">ELU</option>
<option value="swish">Swish</option>
</select>
</div>
</div>
<div class="control ui-optimizer">
<label for="optimizer">Optimizer</label>
<div class="select">
<select id="optimizer">
<option value="sgd">SGD</option>
<option value="momentum">Momentum</option>
<option value="rmsprop">RMSProp</option>
<option value="adam">Adam</option>
</select>
</div>
</div>
Expand Down Expand Up @@ -137,6 +151,20 @@ <h1 class="l--page">Tinker With a <b>Neural Network</b> <span class="optional">R
</select>
</div>
</div>
<div class="control ui-theme">
<button class="mdl-button mdl-js-button mdl-button--icon" id="theme-toggle" title="Toggle dark mode">
<i class="material-icons">brightness_6</i>
</button>
</div>
<div class="control ui-saveload">
<button class="mdl-button mdl-js-button mdl-button--icon" id="save-model-button" title="Save model (weights + biases) as a JSON file">
<i class="material-icons">save</i>
</button>
<button class="mdl-button mdl-js-button mdl-button--icon" id="load-model-button" title="Load a previously saved model JSON file">
<i class="material-icons">folder_open</i>
</button>
<input type="file" id="load-model-input" accept="application/json" style="display:none">
</div>
</div>
</div>

Expand Down Expand Up @@ -189,6 +217,18 @@ <h4>
<p class="slider">
<input class="mdl-slider mdl-js-slider" type="range" id="batchSize" min="1" max="30" step="1">
</p>
</div>
<div class="ui-dropoutRate">
<label for="dropoutRate">Dropout rate:&nbsp;&nbsp;<span class="value">XX</span></label>
<p class="slider">
<input class="mdl-slider mdl-js-slider" type="range" id="dropoutRate" min="0" max="50" step="5">
</p>
</div>
<div class="ui-earlyStopping">
<label for="earlyStopping">
<input type="checkbox" id="earlyStopping">
Early stopping
</label>
</div>
<button class="basic-button" id="data-regen-button" title="Regenerate data">
Regenerate
Expand Down
237 changes: 229 additions & 8 deletions src/nn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ export class Node {
numAccumulatedDers = 0;
/** Activation function that takes total input and returns node's output */
activation: ActivationFunction;
/** Optimizer state: momentum/RMSProp accumulator for the bias. */
biasMoment1 = 0;
/** Optimizer state: Adam second-moment accumulator for the bias. */
biasMoment2 = 0;
/** Dropout mask for the most recent forward pass (1 = kept, 0 = dropped). */
dropoutMask = 1;

/**
* Creates a new node with the provided id and activation function.
Expand All @@ -64,7 +70,7 @@ export class Node {
let link = this.inputLinks[j];
this.totalInput += link.weight * link.source.output;
}
this.output = this.activation.output(this.totalInput);
this.output = this.activation.output(this.totalInput) * this.dropoutMask;
return this.output;
}
}
Expand Down Expand Up @@ -134,6 +140,85 @@ export class Activations {
output: x => x,
der: x => 1
};
public static LEAKY_RELU: ActivationFunction = {
output: x => x >= 0 ? x : 0.01 * x,
der: x => x >= 0 ? 1 : 0.01
};
public static ELU: ActivationFunction = {
output: x => x >= 0 ? x : Math.exp(x) - 1,
der: x => x >= 0 ? 1 : Math.exp(x)
};
public static SWISH: ActivationFunction = {
output: x => x / (1 + Math.exp(-x)),
der: x => {
let sigmoid = 1 / (1 + Math.exp(-x));
let swish = x * sigmoid;
return swish + sigmoid * (1 - swish);
}
};
}

/** Supported weight-update strategies. */
export type OptimizerType = "sgd" | "momentum" | "rmsprop" | "adam";

/** Configuration for the weight-update step. */
export interface OptimizerConfig {
type: OptimizerType;
/** Current optimization step, 1-indexed. Used for Adam's bias correction. */
t: number;
momentum?: number;
beta1?: number;
beta2?: number;
epsilon?: number;
/** Maximum allowed L2 norm of any single gradient; 0 disables clipping. */
gradientClip?: number;
/** Multiplicative learning-rate decay applied once per call (0 disables). */
learningRateDecay?: number;
}

const DEFAULT_OPTIMIZER: OptimizerConfig = {type: "sgd", t: 1};

/**
* Computes the actual step to apply to a parameter given its averaged
* gradient, using the requested optimizer. Mutates the per-parameter
* moment1/moment2 accumulators in place.
*/
function computeStep(grad: number, learningRate: number,
state: {moment1: number, moment2: number}, config: OptimizerConfig):
number {
if (config.gradientClip && config.gradientClip > 0) {
let clip = config.gradientClip;
if (grad > clip) {
grad = clip;
} else if (grad < -clip) {
grad = -clip;
}
}
switch (config.type) {
case "momentum": {
let momentum = config.momentum != null ? config.momentum : 0.9;
state.moment1 = momentum * state.moment1 + grad;
return learningRate * state.moment1;
}
case "rmsprop": {
let decay = config.beta2 != null ? config.beta2 : 0.9;
let epsilon = config.epsilon != null ? config.epsilon : 1e-8;
state.moment2 = decay * state.moment2 + (1 - decay) * grad * grad;
return learningRate * grad / (Math.sqrt(state.moment2) + epsilon);
}
case "adam": {
let beta1 = config.beta1 != null ? config.beta1 : 0.9;
let beta2 = config.beta2 != null ? config.beta2 : 0.999;
let epsilon = config.epsilon != null ? config.epsilon : 1e-8;
state.moment1 = beta1 * state.moment1 + (1 - beta1) * grad;
state.moment2 = beta2 * state.moment2 + (1 - beta2) * grad * grad;
let mHat = state.moment1 / (1 - Math.pow(beta1, config.t));
let vHat = state.moment2 / (1 - Math.pow(beta2, config.t));
return learningRate * mHat / (Math.sqrt(vHat) + epsilon);
}
default:
return learningRate * grad;
}
}

/** Build-in regularization functions */
Expand Down Expand Up @@ -167,6 +252,10 @@ export class Link {
/** Number of accumulated derivatives since the last update. */
numAccumulatedDers = 0;
regularization: RegularizationFunction;
/** Optimizer state: momentum/RMSProp accumulator (first moment). */
moment1 = 0;
/** Optimizer state: Adam second-moment accumulator. */
moment2 = 0;

/**
* Constructs a link in the neural network initialized with random weight.
Expand Down Expand Up @@ -250,7 +339,9 @@ export function buildNetwork(
* nodes in the network.
* @return The final output of the network.
*/
export function forwardProp(network: Node[][], inputs: number[]): number {
export function forwardProp(network: Node[][], inputs: number[],
dropoutRate = 0, isTraining = false, rng: () => number = Math.random):
number {
let inputLayer = network[0];
if (inputs.length !== inputLayer.length) {
throw new Error("The number of inputs must match the number of nodes in" +
Expand All @@ -261,11 +352,19 @@ export function forwardProp(network: Node[][], inputs: number[]): number {
let node = inputLayer[i];
node.output = inputs[i];
}
let lastLayerIdx = network.length - 1;
for (let layerIdx = 1; layerIdx < network.length; layerIdx++) {
let currentLayer = network[layerIdx];
// Dropout only ever applies to hidden layers, and only while training.
let applyDropout = isTraining && dropoutRate > 0 && layerIdx !== lastLayerIdx;
// Update all the nodes in this layer.
for (let i = 0; i < currentLayer.length; i++) {
let node = currentLayer[i];
if (applyDropout) {
node.dropoutMask = rng() < dropoutRate ? 0 : 1 / (1 - dropoutRate);
} else {
node.dropoutMask = 1;
}
node.updateOutput();
}
}
Expand Down Expand Up @@ -333,14 +432,19 @@ export function backProp(network: Node[][], target: number,
* derivatives.
*/
export function updateWeights(network: Node[][], learningRate: number,
regularizationRate: number) {
regularizationRate: number, optimizer: OptimizerConfig = DEFAULT_OPTIMIZER) {
if (optimizer.learningRateDecay && optimizer.learningRateDecay > 0) {
learningRate = learningRate /
(1 + optimizer.learningRateDecay * (optimizer.t - 1));
}
for (let layerIdx = 1; layerIdx < network.length; layerIdx++) {
let currentLayer = network[layerIdx];
for (let i = 0; i < currentLayer.length; i++) {
let node = currentLayer[i];
// Update the node's bias.
if (node.numAccumulatedDers > 0) {
node.bias -= learningRate * node.accInputDer / node.numAccumulatedDers;
let grad = node.accInputDer / node.numAccumulatedDers;
node.bias -= computeStepAndUpdate(node, grad, learningRate, optimizer);
node.accInputDer = 0;
node.numAccumulatedDers = 0;
}
Expand All @@ -353,10 +457,12 @@ export function updateWeights(network: Node[][], learningRate: number,
let regulDer = link.regularization ?
link.regularization.der(link.weight) : 0;
if (link.numAccumulatedDers > 0) {
// Update the weight based on dE/dw.
link.weight = link.weight -
(learningRate / link.numAccumulatedDers) * link.accErrorDer;
// Further update the weight based on regularization.
let grad = link.accErrorDer / link.numAccumulatedDers;
// Update the weight based on dE/dw using the configured optimizer.
link.weight -= computeLinkStepAndUpdate(link, grad, learningRate,
optimizer);
// Further update the weight based on regularization (plain SGD
// step on the penalty term, independent of the optimizer above).
let newLinkWeight = link.weight -
(learningRate * regularizationRate) * regulDer;
if (link.regularization === RegularizationFunction.L1 &&
Expand All @@ -375,6 +481,26 @@ export function updateWeights(network: Node[][], learningRate: number,
}
}

/** Applies computeStep against a node's own moment accumulators. */
function computeStepAndUpdate(node: Node, grad: number, learningRate: number,
optimizer: OptimizerConfig): number {
let state = {moment1: node.biasMoment1, moment2: node.biasMoment2};
let step = computeStep(grad, learningRate, state, optimizer);
node.biasMoment1 = state.moment1;
node.biasMoment2 = state.moment2;
return step;
}

/** Applies computeStep against a link's own moment accumulators. */
function computeLinkStepAndUpdate(link: Link, grad: number,
learningRate: number, optimizer: OptimizerConfig): number {
let state = {moment1: link.moment1, moment2: link.moment2};
let step = computeStep(grad, learningRate, state, optimizer);
link.moment1 = state.moment1;
link.moment2 = state.moment2;
return step;
}

/** Iterates over every node in the network/ */
export function forEachNode(network: Node[][], ignoreInputs: boolean,
accessor: (node: Node) => any) {
Expand All @@ -393,3 +519,98 @@ export function forEachNode(network: Node[][], ignoreInputs: boolean,
export function getOutputNode(network: Node[][]) {
return network[network.length - 1][0];
}

/** Plain-data shape of a trained network, safe to JSON.stringify/parse. */
export interface SerializedNetwork {
/** Format version, bumped if the shape of this export ever changes. */
version: 1;
shape: number[];
/** Per-layer, per-node bias (input layer omitted, has no bias). */
biases: number[][];
/** Per-link weight, in the same order buildNetwork() creates links. */
weights: number[][][];
}

/** Serializes a network's weights and biases to a plain-data object. */
export function serializeNetwork(network: Node[][]): SerializedNetwork {
let shape = network.map(layer => layer.length);
let biases: number[][] = [];
let weights: number[][][] = [];
for (let layerIdx = 1; layerIdx < network.length; layerIdx++) {
let layerBiases: number[] = [];
let layerWeights: number[][] = [];
for (let node of network[layerIdx]) {
layerBiases.push(node.bias);
layerWeights.push(node.inputLinks.map(link => link.weight));
}
biases.push(layerBiases);
weights.push(layerWeights);
}
return {version: 1, shape, biases, weights};
}

/**
* Loads previously-serialized weights/biases into a network of matching
* shape. Throws if the shapes don't match, rather than silently applying a
* mismatched subset of values.
*/
export function deserializeNetwork(network: Node[][],
data: SerializedNetwork): void {
let shape = network.map(layer => layer.length);
if (!data || data.version !== 1 || !Array.isArray(data.shape) ||
data.shape.length !== shape.length ||
data.shape.some((n, i) => n !== shape[i])) {
throw new Error("Saved model shape does not match the current network " +
"shape; adjust the number of layers/nodes to match before loading.");
}
for (let layerIdx = 1; layerIdx < network.length; layerIdx++) {
let layerBiases = data.biases[layerIdx - 1];
let layerWeights = data.weights[layerIdx - 1];
let layer = network[layerIdx];
for (let i = 0; i < layer.length; i++) {
let node = layer[i];
let bias = layerBiases[i];
if (typeof bias !== "number" || !isFinite(bias)) {
throw new Error("Saved model contains an invalid bias value.");
}
node.bias = bias;
let nodeWeights = layerWeights[i];
for (let j = 0; j < node.inputLinks.length; j++) {
let weight = nodeWeights[j];
if (typeof weight !== "number" || !isFinite(weight)) {
throw new Error("Saved model contains an invalid weight value.");
}
node.inputLinks[j].weight = weight;
node.inputLinks[j].isDead = false;
}
}
}
}

/**
* Tracks validation loss across calls and reports whether training should
* stop: true once the loss has failed to improve by more than `minDelta`
* for `patience` consecutive checks.
*/
export class EarlyStopping {
private best = Infinity;
private numBadChecks = 0;

constructor(private patience = 10, private minDelta = 1e-4) {}

/** Call once per evaluation interval with the latest validation loss. */
shouldStop(validationLoss: number): boolean {
if (validationLoss < this.best - this.minDelta) {
this.best = validationLoss;
this.numBadChecks = 0;
} else {
this.numBadChecks++;
}
return this.numBadChecks >= this.patience;
}

reset(): void {
this.best = Infinity;
this.numBadChecks = 0;
}
}
Loading
Loading