Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Created July 16, 2021 14:09
Show Gist options
  • Save calebporzio/12e1bab05c3212c23c81aab76cb672e9 to your computer and use it in GitHub Desktop.
Save calebporzio/12e1bab05c3212c23c81aab76cb672e9 to your computer and use it in GitHub Desktop.
<html>
<script src="/basic/canvas.js"></script>
<script src="/basic/ml.js"></script>
<div style="border: 1px solid black; width: 100px; height: 100px;">
<canvas width="200" height="200" id="points" style="position: absolute; width: 100px; height: 100px"></canvas>
<canvas width="200" height="200" id="line" style="position: absolute; width: 100px; height: 100px"></canvas>
</div>
<script>
let points = [
[-1, .75],
[0, 2.1],
[1, 2],
[2.2, 3.9],
[2.5, 5],
[4.4, 6.2],
[4.8, 7.2],
[6.7, 8.2],
[7.1, 8.8],
[8.1, 9.6],
]
let model = {
slope: 0,
offset: 0,
}
drawPoints(points)
function recurse(current, total) {
setTimeout(() => {
train(model, points)
drawLine(model.slope, model.offset)
if (current < total) recurse(current + 1, total)
}, 100)
}
recurse(0, 1000)
function train(model, points) {
let predict = (x) => model.slope * x + model.offset
for (let i = 0; i < points.length; i++) {
let [x, y] = points[i];
let diff = y - predict(x)
model.slope += .01 * diff * x
model.offset += .01 * diff
}
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment