JS Perceptron
Perceptron by JavaScript, this is XOR problem demo.
by Tinytsunami
HTML
<div id="demo">
<canvas></canvas>
<pre>click radio button to start.</pre>
<form>
<input name="type" type="radio" value="not" /> NOT
<input name="type" type="radio" value="or" /> OR
<input name="type" type="radio" value="and" /> AND
<input name="type" type="radio" value="xor" /> XOR
</form>
</div>
CSS
body {
color: #ffffff;
background: #20262e;
font-family: monospace, sans-serif;
}
#demo {
padding: 5px;
}
#demo canvas {
border: solid 1px #ffffff;
}
#demo pre {
width: 400px;
border: solid 1px #ffffff;
}
#demo button {
color: #ffffff;
background: #20262e;
border: 1px solid #ffffff;
outline: none;
}
#demo button:hover {
color: #20262e;
background: #ffffff;
border: 1px solid #ffffff;
}
JavaScript
(function() {
/* get elements */
let root = document.getElementById("demo");
let canvas = root.getElementsByTagName("canvas")[0];
let context = canvas.getContext("2d");
let log = root.getElementsByTagName("pre")[0];
let inputs = root.getElementsByTagName("input");
for(let i = 0; i < inputs.length; i++) {
inputs[i].onchange = function(){
// find index of radio
let select = Array.from(inputs).map(function(item){
return item.checked;
}).indexOf(true);
//start
refresh(select);
};
}
/* canvas style */
const SIZE = 200;
let pointSize = 2;
let lineXYColor = "#eeeeee";
/* initialize canvas */
canvas.width = SIZE * 2;
canvas.height = SIZE * 2;
context.translate(SIZE, SIZE);
let refreshCanvas = function() {
context.clearRect(-SIZE, -SIZE, SIZE, SIZE);
drawLine(0, -SIZE, 0, SIZE, lineXYColor);
drawLine(-SIZE, 0, SIZE, 0, lineXYColor);
if(data) {
testH();
}
};
/* test hypothesis in {0, 1, ..., 10} */
let testH = function() {
for(let x1 = 0; x1 <= 10; x1++) {
for(let x2 = 0; x2 <= 10; x2++) {
let y = h([1, x1 / 10, x2 / 10]);
drawPoint(x1 * 10, x2 * 10, getColor(y));
}
}
};
let reSize = function(v) {
return 100 * v;
};
/* format CSS color code */
let format = function(str){
return str.length == 1 ? "0" + str : str;
};
/* get point color(hypothesis result) */
let getColor = function(y) {
let value = Math.abs(Math.ceil(y * 255));
let red = format(value.toString(16));
let blue = format((255 - value).toString(16));
let color = `#${red}00${blue}`;
return color;
};
/* draw point to canvas */
let drawPoint = function(x, y, color){
context.strokeStyle = color;
context.beginPath();
context.arc(x, -y, pointSize, 0, 2*Math.PI);
context.closePath();
context.stroke();
};
/* draw line to canvas */
let drawLine = function(x1, y1, x2, y2, color){
...