Skip to content

Instantly share code, notes, and snippets.

@chalkpe
Created December 19, 2016 09:45
Show Gist options
  • Save chalkpe/501efbd8d6e74d80181f72ea69aee892 to your computer and use it in GitHub Desktop.
Save chalkpe/501efbd8d6e74d80181f72ea69aee892 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Linear regression</title>
<style media="screen">
body {
margin: 0;
overflow: hidden;
}
#information {
position: absolute;
top: 10px; left: 10px;
font-size: 16px;
font-family: 'Fira Code', monospace;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="information"></div>
<script type="text/javascript">
let width, height, ctx, list = [];
let [aa, bb, bestVA, bestAA, bestBB] = [0.5, 99, Infinity];
let [r, a, b, c] = [1, 0.5 + Math.random(), Math.random() * 100 + 100, 500];
function drawDots(){
ctx.fillStyle = '#fcfcfc';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'red';
for(let x = 0; x < width * r; x++)
ctx.fillRect(x / r, height - list[x / r], 2, 2);
}
function drawLine(a, b, color = 'gray'){
ctx.beginPath();
ctx.moveTo(0, height - b);
ctx.lineTo(width, height - (a * width + b));
ctx.strokeStyle = color;
ctx.stroke();
}
function learn(){
if(bb >= 200) return;
if(aa >= 3){
bb += Math.random();
aa = 0.5; drawDots();
}
let va = 0;
for(let x = 0; x < width * r; x++){
let y = x * aa + bb;
va += Math.pow(list[x] - y, 2);
}
if(va < bestVA) [bestAA, bestBB, bestVA] = [aa, bb, va];
information.innerHTML = [a, b, '', bestAA, bestBB, '', aa, bb].join('<br>');
[[a, b], [aa, bb, '#eeeeee'], [bestAA, bestBB, '#8bc34a']].forEach(args => drawLine(...args));
aa += Math.random() / 100;
setTimeout(learn, 0);
}
let superAwesomeRandom = (n = 5) =>
[...Array(n)].reduce((a, b) => a + Math.random(), 0) / n;
let populate = () => {
for(let x = 0; x < width * r; x++)
list[x] = a * x + b + (superAwesomeRandom() * 2 * c) - c;
};
document.addEventListener('DOMContentLoaded', event => {
let canvas = document.getElementById('canvas');
let information = document.getElementById('information');
ctx = canvas.getContext('2d');
({ innerWidth: width, innerHeight: height } = window);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
populate(), drawDots(), learn();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment