Build Your Own MLP
Here's a minimal 2-layer MLP for XOR using standard libraries only.
xxxxxxxxxx
91
}
function randu(a, b) { return a + (b - a) * Math.random(); }
function sigmoid(x) { return 1 / (1 + Math.exp(-x)); }
function dsigmoid(y) { return y * (1 - y); }
function relu(x) { return x > 0 ? x : 0; }
function reluGrad(x) { return x > 0 ? 1 : 0; }
function matvec(W, v) {
const out = new Array(W.length).fill(0);
for (let r = 0; r < W.length; r++) {
let s = 0;
for (let c = 0; c < v.length; c++) s += W[r][c] * v[c];
out[r] = s;
}
return out;
}
function addv(a, b) { return a.map((x, i) => x + b[i]); }
function trainXOR(epochs = 5000, lr = 0.1, hidden = 4) {
// XOR dataset
const X = [[0,0],[0,1],[1,0],[1,1]];
const Y = [0,1,1,0];
// Params
const inputDim = 2;
let W1 = Array.from({length: hidden}, () => Array.from({length: inputDim}, () => randu(-1,1)));
let b1 = Array.from({length: hidden}, () => 0);
let W2 = Array.from({length: hidden}, () => randu(-1,1));
let b2 = 0;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment