Skip to content

Instantly share code, notes, and snippets.

@jmlavoier
Last active February 23, 2026 17:56
Show Gist options
  • Select an option

  • Save jmlavoier/d96db6e87da99e8686fdc13745474b48 to your computer and use it in GitHub Desktop.

Select an option

Save jmlavoier/d96db6e87da99e8686fdc13745474b48 to your computer and use it in GitHub Desktop.
const x = [
[0.3, 0.7, 1],
[-0.6, 0.3, 0 ],
[-0.1, -0.8, 0],
[0.1, -0.45, 1],
];
const log = ({ i, w1n, w2n, w1, w2, n, e, x1, x2 }) => {
console.log(`i: ${i}`);
console.log(`w1: ${w1n} = ${w1}+${n}*${e}*${x1}`);
console.log(`w2: ${w2n} = ${w2}+${n}*${e}*${x2}`);
console.log(`w1: ${w1n} w2: ${w2n}`);
console.log('########################');
}
const createPerceptron = ({ x, w, n }) => {
let w1 = w[1];
let w2 = w[2];
const lossFn = (value) => value >= 0 ? 1 : 0;
for (let i = 0; i < x.length; i += 1) {
const [x1, x2, c] = x[i];
const o = lossFn((x1*w1)+(x2*w2));
const e = c - o;
if (o != c) {
const w1n = parseFloat((w1+n*e*x1).toFixed(4));
const w2n = parseFloat((w2+n*e*x2).toFixed(4));
log({ i, w1n, w2n, w1, w2, n, e, x1, x2 });
w1 = w1n;
w2 = w2n;
}
}
return ({ x1, x2 }) => {
return lossFn((x1*w1)+(x2*w2));
}
}
const perceptron = createPerceptron({ x, w: { 1: 0.8, 2: -0.5 }, n: 0.5 });
console.log(`result: ${perceptron({ x1: -0.5, x2: 0.4 })}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment