-
Notifications
You must be signed in to change notification settings - Fork 0
/
sketch.js
68 lines (53 loc) · 1.39 KB
/
sketch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
let x_vals = [];
let y_vals = [];
let m, b;
const learningRate = 0.5;
const optimizer = tf.train.sgd(learningRate);
function setup() {
createCanvas(400, 400);
m = tf.variable(tf.scalar(random(1)));
b = tf.variable(tf.scalar(random(1)));
}
function loss(pred, labels) {
return pred.sub(labels).square().mean();
}
function predict(x) {
const xs = tf.tensor1d(x);
// y = mx + b;
const ys = xs.mul(m).add(b);
return ys;
}
function mousePressed() {
let x = map(mouseX, 0, width, 0, 1);
let y = map(mouseY, 0, height, 1, 0);
x_vals.push(x);
y_vals.push(y);
}
function draw() {
tf.tidy(() => {
if (x_vals.length > 0) {
const ys = tf.tensor1d(y_vals);
optimizer.minimize(() => loss(predict(x_vals), ys));
}
});
background(0);
stroke(255);
strokeWeight(8);
for (let i = 0; i < x_vals.length; i++) {
let px = map(x_vals[i], 0, 1, 0, width);
let py = map(y_vals[i], 0, 1, height, 0);
point(px, py);
}
const lineX = [0, 1];
const ys = tf.tidy(() => predict(lineX));
let lineY = ys.dataSync();
ys.dispose();
let x1 = map(lineX[0], 0, 1, 0, width);
let x2 = map(lineX[1], 0, 1, 0, width);
let y1 = map(lineY[0], 0, 1, height, 0);
let y2 = map(lineY[1], 0, 1, height, 0);
strokeWeight(2);
line(x1, y1, x2, y2);
console.log(tf.memory().numTensors);
//noLoop();
}