class ANN {
constructor(t = [2, 2, 2], n = [sigmoid, sigmoid], e = .2, i = !1) {
this.structure = t, this.activation = n, this.lr = e, this.bias = i, this.x = this.generateLayers(), this.w = this.generateWeights(), this.activation.splice(0, 0, null), this.trainingExampleFed = 0, this.testingExampleFed = 0, this.rightPrediction = 0
}
generateLayers() {
let t = [];
for (let n in this.structure) t.push(new Matrix(this.structure[n], 1));
return t
}
generateWeights() {
let t = this.structure.length - 1, n = new Array(t - 1);
n[0] = null;
for (let e = 0; e < t; e++) {
let t = this.x[e].rows, i = this.x[e + 1].rows;
n[e + 1] = new Matrix(i, t), n[e + 1].randomize()
}
return n
}
net(t) {
return Matrix.multiply(this.w[t], this.x[t - 1])
}
act(t) {
return this.net(t).map(this.activation[t].func)
}
onlyPropagate(t) {
t = this.transformInput(t), this.x[0] = t;
for (let t = 1; t < this.x.length; t++) this.x[t] = this.act(t)
}
propagate(t) {
this.x[0] = t;
for (let t = 1; t < this.x.length; t++) this.x[t] = this.act(t)
}
calculateError(t) {
let n = 0;
for (let e in t.data)
for (let i in t.data[e]) n += Math.pow(t.data[e][i] - this.x[this.x.length - 1].data[e][i], 2) / 2;
return n
}
backpropagate(t) {
let n = [], e = Matrix.subtract(t, this.x[this.x.length - 1]), i = Matrix.map(this.x[this.x.length - 1], this.activation[this.x.length - 1].dfunc);
i.multiply(e), i.multiply(this.lr);
let s = Matrix.multiply(i, Matrix.transpose(this.x[this.x.length - 2]));
this.w[this.x.length - 1].add(s), n[this.x.length - 1] = e;
for (let t = this.x.length - 2; t > 0; t--) {
let e = Matrix.multiply(Matrix.transpose(this.w[t + 1]), n[t + 1]), i = Matrix.map(this.x[t], this.activation[t].dfunc);
i.multiply(e), i.multiply(this.lr);
let s = Matrix.multiply(i, Matrix.transpose(this.x[t - 1]));
this.w[t].add(s), n[t] = e
}
}
backpropagateCodingTrain(t) {
let n = [], e = Matrix.subtract(t, this.x[this.x.length - 1]), i = Matrix.map(this.x[this.x.length - 1], this.activation[this.x.length - 1].dfunc);
i.multiply(e), i.multiply(this.lr);
let s = Matrix.multiply(i, Matrix.transpose(this.x[this.x.length - 2]));
this.w[this.x.length - 1].add(s), n[this.x.length - 1] = e;
for (let t = this.x.length - 2; t > 0; t--) {
let e = Matrix.multiply(Matrix.transpose(this.w[t + 1]), n[t + 1]), i = Matrix.map(this.x[t], this.activation[t].dfunc);
i.multiply(e), i.multiply(this.lr);
let s = Matrix.multiply(i, Matrix.transpose(this.x[t - 1]));
this.w[t].add(s), n[t] = e
}
}
train(t, n) {
t = this.transformInput(t), n = this.transformtarget(n), this.propagate(t), this.backpropagate(n);
let e = outNumeric(n), i = this.getPrediction();
this.trainingExampleFed += 1, console.log("error: ", this.calculateError(n).toFixed(4), " target: ", e, " prediction: ", i, " examples fed: ", this.trainingExampleFed, e == i ? "GOT IT" : " ")
}
test(t, n) {
t = this.transformInput(t), n = this.transformtarget(n), this.propagate(t);
let e = outNumeric(n), i = this.getPrediction();
this.testingExampleFed += 1, e == i && (this.rightPrediction += 1), console.log("error: ", this.calculateError(n).toFixed(4), " target: ", e, " prediction: ", i, " precision: ", this.rightPrediction, "/", this.testingExampleFed, e == i ? "GOT IT" : " ")
}
getPrediction() {
return outNumeric(this.x[this.x.length - 1])
}
transformInput(t) {
return t = (t = Array.from(t)).map(t = t / 255), t = Matrix.fromArray(t)
}
transformtarget(t) {
return t = outOneHot(this.structure[this.structure.length - 1], t), t = Matrix.fromArray(t)
}
generateHtml() {
return '\n <div id="ANNGenerator"><h4>Artificial Neural Network</h4>\n <p class="ANNSubtitle"><i>customize it</i></p>\n ' + this.generateInputSection() + "\n " + this.generateHiddenSections() + "\n " + this.generateOutputSection() + "\n </div>\n "
}
generateInputSection() {
return '\n <div class="ANNSection">\n <div class="ANNTitleContainer">\n <span class="ANNTitle"><b>Input layer</b></span>\n <span class="ANNFunction"></span>\n </div>\n <div class="ANNCenter"># of Neurons: <b>' + this.structure[0] + '</b></div>\n <div class="ANNNeurons"><b><i>I</i></b><sub>0</sub> ... <b><i>I</i></b><sub>' + (this.structure[0] - 1) + "</sub></div>\n </div>\n "
}
generateHiddenSection(t) {
return '\n <div class="ANNSectionAdd" onclick="nn.createNewLayer(' + t + ')">\n <b>+</b>\n </div>\n <div class="ANNSection" id="hiddenLayer' + t + '">\n <div class="ANNTitleContainer">\n <span class="ANNTitle"><b>Hidden ' + t + ' layer</b></span>\n <span class="ANNFunction">f = ' + this.activation[t].name + '</span>\n </div>\n <div class="ANNCenter"># of Neurons: <b>' + this.structure[t] + '</b></div>\n <div class="ANNNeurons">\n <span class="ANNNeuronNames">\n <b><i>H' + t + "</i></b><sub>0</sub> ... \n <b><i>H" + t + "</i></b><sub>" + (this.structure[t] - 1) + '</sub>\n </span>\n <span class="ANNSettings">\n <span class="jsLink" onclick="$(\'#hiddenLayer' + t + "').html(nn.generateHiddenSectionSettings(" + t + '))">change settings</span>\n <span>\n </div>\n </div>\n '
}
generateHiddenSectionSettings(t) {
return '\n <div class="ANNSection" id="hiddenLayer' + t + '">\n <div class="ANNTitleContainer">\n <span class="ANNTitle"><b>Hidden ' + t + ' layer</b></span>\n <span class="ANNFunction">' + this.activationFunctionSelection("hidFunction" + t) + '</span>\n </div>\n <div class="ANNCenter"># of Neurons: \n <input type="number" id="hidNumber' + t + '" value="' + this.structure[t] + '">\n </div>\n <div class="ANNNeurons">\n <span class="ANNNeuronNames">\n <b><i>H' + t + "</i></b><sub>0</sub> ... \n <b><i>H" + t + "</i></b><sub>" + (this.structure[t] - 1) + '</sub>\n </span>\n <span class="ANNSettings">\n <span class="jsLink" onclick="nn.updateHiddenSettings(' + t + ", $('#hidNumber" + t + "').val(), $('#hidFunction" + t + "').val())\">save settings</span>\n <span>\n </div>\n </div>\n "
}
updateHiddenSettings(t, n, e) {
this.structure[t] = Number(n), this.activation[t] = allFunctions[Number(e)], this.x = this.generateLayers(), this.w = this.generateWeights(), this.writeHtmlOnPage()
}
generateOutputSectionSettings() {
return '\n <div class="ANNTitleContainer">\n <span class="ANNTitle"><b>Output layer</b></span>\n <span class="ANNFunction">' + this.activationFunctionSelection("outFunction") + ' </span>\n </div>\n <div class="ANNCenter"># of Neurons: \n <input type="number" id="outNumber" value="' + this.structure[this.structure.length - 1] + '">\n </div>\n <div class="ANNNeurons">\n <span class="ANNNeuronNames">\n <b><i>O</i></b><sub>0</sub> ... \n <b><i>O</i></b><sub>' + (this.structure[this.structure.length - 1] - 1) + '</sub>\n </span>\n <span class="ANNSettings">\n <span class="jsLink" onclick="nn.updateOutputSettings($(\'#outNumber\').val(), $(\'#outFunction\').val())">save settings</span>\n <span>\n </div>\n '
}
generateHiddenSections() {
let t = "";
for (let n = 1; n < this.structure.length - 1; n++) t += this.generateHiddenSection(n);
return t
}
generateOutputSection() {
return '\n <div class="ANNSectionAdd" onclick="nn.createNewLayer(' + (this.structure.length - 1) + ')">\n <b>+</b>\n </div>\n <div class="ANNSection" id="outputLayer">\n <div class="ANNTitleContainer">\n <span class="ANNTitle"><b>Output layer</b></span>\n <span class="ANNFunction">f = ' + this.activation[this.structure.length - 1].name + ' </span>\n </div>\n <div class="ANNCenter"># of Neurons: <b>' + this.structure[this.structure.length - 1] + '</b></div>\n <div class="ANNNeurons">\n <span class="ANNNeuronNames">\n <b><i>O</i></b><sub>0</sub> ... \n <b><i>O</i></b><sub>' + (this.structure[this.structure.length - 1] - 1) + '</sub>\n </span>\n <span class="ANNSettings">\n <span class="jsLink" onclick="$(\'#outputLayer\').html(nn.generateOutputSectionSettings())">change settings</span>\n <span>\n </div>\n </div>\n '
}
generateOutputSectionSettings() {
return '\n <div class="ANNTitleContainer">\n <span class="ANNTitle"><b>Output layer</b></span>\n <span class="ANNFunction">' + this.activationFunctionSelection("outFunction") + ' </span>\n </div>\n <div class="ANNCenter"># of Neurons: \n <input type="number" id="outNumber" value="' + this.structure[this.structure.length - 1] + '">\n </div>\n <div class="ANNNeurons">\n <span class="ANNNeuronNames">\n <b><i>O</i></b><sub>0</sub> ... \n <b><i>O</i></b><sub>' + (this.structure[this.structure.length - 1] - 1) + '</sub>\n </span>\n <span class="ANNSettings">\n <span class="jsLink" onclick="nn.updateOutputSettings($(\'#outNumber\').val(), $(\'#outFunction\').val())">save settings</span>\n <span>\n </div>\n '
}
updateOutputSettings(t, n) {
this.structure[this.structure.length - 1] = Number(t), this.activation[this.activation.length - 1] = allFunctions[Number(n)], this.x = this.generateLayers(), this.w = this.generateWeights(), this.writeHtmlOnPage()
}
activationFunctionSelection(t) {
let n = "";
for (let t in allFunctions) n += '<option value="' + t + '">' + allFunctions[t].name + "</option>";
return '\n <label for="' + t + '">f = </label>\n <select id="' + t + '">\n ' + n + "\n </select> \n "
}
createNewLayer(t) {
this.structure.splice(t, 0, 2), this.activation.splice(t, 0, allFunctions[0]), this.x = this.generateLayers(), this.w = this.generateWeights(), this.writeHtmlOnPage()
}
writeHtmlOnPage() {
$("#ANNDiv").html(this.generateHtml())
}
}
const PIXELS = 28, PIXELSSQUARED = PIXELS * PIXELS, NOTRAIN = 6e4, NOTEST = 1e4, noinput = PIXELSSQUARED, nohidden = 64, nooutput = 10, learningrate = .1;
let do_training = !0;
const TRAINPERSTEP = 30, TESTPERSTEP = 5, ZOOMFACTOR = 7, ZOOMPIXELS = 7 * PIXELS, canvaswidth = PIXELS, canvasheight = PIXELS, DOODLE_THICK = 18, DOODLE_BLUR = 3;
let mnist, nn, doodle, demo, trainrun = 1, train_index = 0, testrun = 1, test_index = 0, total_tests = 0, total_correct = 0, doodle_exists = !1, demo_exists = !1, mousedrag = !1;
var train_inputs, test_inputs, demo_inputs, doodle_inputs, thehtml;
AB.headerCSS({
"max-height": "95vh"
}), thehtml = "<hr> <h1> 1. Doodle </h1> Top row: Doodle (left) and shrunk (right). <br> Draw your doodle in top LHS. <button onclick='wipeDoodle();' class='normbutton' >Clear doodle</button> <br> ", AB.msg(thehtml, 1), thehtml = "<hr> <h1> 2. Training </h1> Middle row: Training image magnified (left) and original (right). <br> <button onclick='do_training = false;' class='normbutton' >Stop training</button> <br> ", AB.msg(thehtml, 3), thehtml = "<h3> Hidden tests </h3> ", AB.msg(thehtml, 5), thehtml = "<hr> <h1> 3. Demo </h1> Bottom row: Test image magnified (left) and original (right). <br> The network is <i>not</i> trained on any of these images. <br> <button onclick='makeDemo();' class='normbutton' >Demo test image</button> <br> ", AB.msg(thehtml, 7);
const greenspan = "<span style='font-weight:bold; font-size:x-large; color:darkgreen'> ";
function loadCss(t) {
var n = document.getElementsByTagName("head")[0],
e = document.createElement("link");
e.rel = "stylesheet", e.type = "text/css", e.href = t, e.media = "all", n.appendChild(e)
}
function setup() {
let t, n = [PIXELSSQUARED, 64, 64, 10];
createDiv("bla").id("ANNDiv"), $("#ANNDiv").css("display", "inline-block"), $("#ab-wrapper").css("display", "none"), loadCss("https://ancientbrain.com/uploads/stefano/general_ann_style.css"), loadCss("https://fonts.googleapis.com/css2?family=Noto+Serif:ital,wght@1,700&family=Nunito:wght@300&display=swap"), createCanvas(canvaswidth, canvasheight), background(220), AB.loadingScreen(), $.getScript("/uploads/codingtrain/matrix.js", function() {
$.getScript("/uploads/stefano/utils.js", function() {
$.getScript("/uploads/stefano/generalANN.js", function() {
$.getScript("/uploads/codingtrain/mnist.js", function() {
console.log("All JS loaded"), t = [sigmoid, sigmoid, sigmoid], nn = new ANN(n, t, .1, !1), loadData(), nn.writeHtmlOnPage()
})
})
})
})
}
function loadData() {
loadMNIST(function(t) {
mnist = t, console.log("All data loaded into mnist object:"), console.log(mnist), AB.removeLoading()
})
}
function getImage(t) {
let n = createImage(PIXELS, PIXELS);
n.loadPixels();
for (let e = 0; e < PIXELSSQUARED; e++) {
let i = t[e], s = 4 * e;
n.pixels[s + 0] = i, n.pixels[s + 1] = i, n.pixels[s + 2] = i, n.pixels[s + 3] = 255
}
return n.updatePixels(), n
}
function getInputs(t) {
let n = [];
for (let e = 0; e < PIXELSSQUARED; e++) {
let i = t[e];
n[e] = i / 255
}
return n
}
function trainit(t) {
let n = mnist.train_images[train_index], e = mnist.train_labels[train_index];
if (t) {
var i = getImage(n);
image(i, 0, ZOOMPIXELS + 50, ZOOMPIXELS, ZOOMPIXELS), image(i, ZOOMPIXELS + 50, ZOOMPIXELS + 50, PIXELS, PIXELS)
}
let s = getInputs(n), a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
a[e] = 1, train_inputs = s, nn.train(s, a), thehtml = " trainrun: " + trainrun + "<br> no: " + train_index, AB.msg(thehtml, 4), ++train_index == NOTRAIN && (train_index = 0, console.log("finished trainrun: " + trainrun), trainrun++)
}
function testit() {
let t = mnist.test_images[test_index], n = mnist.test_labels[test_index], e = getInputs(t);
test_inputs = e;
let i = findMax(nn.predict(e));
total_tests++, i == n && total_correct++;
let s = total_correct / total_tests * 100;
thehtml = " testrun: " + testrun + "<br> no: " + total_tests + " <br> correct: " + total_correct + "<br> score: " + greenspan + s.toFixed(2) + "</span>", AB.msg(thehtml, 6), ++test_index == NOTEST && (console.log("finished testrun: " + testrun + " score: " + s.toFixed(2)), testrun++, test_index = 0, total_tests = 0, total_correct = 0)
}
function find12(t) {
let n = 0, e = 0, i = 0, s = 0;
for (let a = 0; a < t.length; a++) t[a] > i ? (e = n, s = i, n = a, i = t[a]) : t[a] > s && (e = a, s = t[a]);
return [n, e]
}
function findMax(t) {
let n = 0, e = 0;
for (let i = 0; i < t.length; i++) t[i] > e && (n = i, e = t[i]);
return n
}
function draw() {}
function makeDemo() {
demo_exists = !0;
var t = AB.randomIntAtoB(0, NOTEST - 1);
demo = mnist.test_images[t];
var n = mnist.test_labels[t];
thehtml = "Test image no: " + t + "<br>Classification: " + n + "<br>", AB.msg(thehtml, 8)
}
function drawDemo() {
var t = getImage(demo);
image(t, 0, canvasheight - ZOOMPIXELS, ZOOMPIXELS, ZOOMPIXELS), image(t, ZOOMPIXELS + 50, canvasheight - ZOOMPIXELS, PIXELS, PIXELS)
}
function guessDemo() {
let t = getInputs(demo);
demo_inputs = t;
let n = findMax(nn.predict(t));
thehtml = " We classify it as: " + greenspan + n + "</span>", AB.msg(thehtml, 9)
}
function drawDoodle() {
let t = doodle.get();
image(t, 0, 0, ZOOMPIXELS, ZOOMPIXELS), image(t, ZOOMPIXELS + 50, 0, PIXELS, PIXELS)
}
function guessDoodle() {
let t = doodle.get();
t.resize(PIXELS, PIXELS), t.loadPixels();
let n = [];
for (let e = 0; e < PIXELSSQUARED; e++) n[e] = t.pixels[4 * e] / 255;
doodle_inputs = n;
let e = find12(nn.predict(n));
thehtml = " We classify it as: " + greenspan + e[0] + "</span> <br> No.2 guess is: " + greenspan + e[1] + "</span>", AB.msg(thehtml, 2)
}
function wipeDoodle() {
doodle_exists = !1, doodle.background("black")
}
function showInputs(t) {
var n = "";
for (let e = 0; e < t.length; e++) {
e % PIXELS == 0 && (n += "\n"), n = n + " " + t[e].toFixed(2)
}
console.log(n)
}
function executeTraining() {
for (let t = 0; t < 6e3; t++) nn.train(mnist.train_images[t], mnist.train_labels[t])
}
function executeTesting() {
for (let t = 0; t < 1e3; t++) nn.test(mnist.test_images[t], mnist.test_labels[t])
}