-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathsketch.js
98 lines (82 loc) · 1.9 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Polynomial Regression with TensorFlow.js
// Video: https://youtu.be/tIXDik5SGsI
let x_vals = [];
let y_vals = [];
let a, b, c, d;
let dragging = false;
const learningRate = 0.2;
const optimizer = tf.train.adam(learningRate);
function setup() {
createCanvas(400, 400);
a = tf.variable(tf.scalar(random(-1, 1)));
b = tf.variable(tf.scalar(random(-1, 1)));
c = tf.variable(tf.scalar(random(-1, 1)));
d = tf.variable(tf.scalar(random(-1, 1)));
}
function loss(pred, labels) {
return pred
.sub(labels)
.square()
.mean();
}
function predict(x) {
const xs = tf.tensor1d(x);
// y = ax^3 + bx^2 + cx + d
const ys = xs
.pow(tf.scalar(3))
.mul(a)
.add(xs.square().mul(b))
.add(xs.mul(c))
.add(d);
return ys;
}
function mousePressed() {
dragging = true;
}
function mouseReleased() {
dragging = false;
}
function draw() {
if (dragging) {
let x = map(mouseX, 0, width, -1, 1);
let y = map(mouseY, 0, height, 1, -1);
x_vals.push(x);
y_vals.push(y);
} else {
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], -1, 1, 0, width);
let py = map(y_vals[i], -1, 1, height, 0);
point(px, py);
}
const curveX = [];
for (let x = -1; x <= 1; x += 0.05) {
curveX.push(x);
}
const ys = tf.tidy(() => predict(curveX));
let curveY = ys.dataSync();
ys.dispose();
beginShape();
noFill();
stroke(255);
strokeWeight(2);
for (let i = 0; i < curveX.length; i++) {
let x = map(curveX[i], -1, 1, 0, width);
let y = map(curveY[i], -1, 1, height, 0);
vertex(x, y);
}
endShape();
// console.log(tf.memory().numTensors);
}