Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Created Jul 16, 2021
Embed
What would you like to do?
<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