Public
Edited
Apr 22, 2023
Insert cell
Insert cell
Insert cell
(await visibility(),
p5((sketch) => {
sketch.setup = () => {
sketch.createCanvas(width, height);
};

sketch.draw = () => {
sketch.background(255);
drawMesh(sketch);
drawData(sketch);
};

sketch.mouseClicked = () => {
if (
(sketch.mouseX >= 0) &
(sketch.mouseX <= width) &
(sketch.mouseY >= 0) &
(sketch.mouseY <= height)
)
addPoint(sketch);
};
}))
Insert cell
data = []
Insert cell
width = 400
Insert cell
height = 400
Insert cell
meshSize = 10
Insert cell
mesh
Insert cell
mesh = _.range(meshSize).flatMap((x) =>
_.range(meshSize).flatMap(
(y) =>
new Object({
x: ((x + 0.5) * width) / meshSize,
y: ((y + 0.5) * height) / meshSize,
cls: "a",
confidence: 0,
})
)
)
Insert cell
clsContainer = new Object({"cls": "a"})
Insert cell
clsContainer.cls = cls
Insert cell
drawMesh = (sketch) => {
mesh.forEach((pt) => {
let color = sketch.color(colors.get(pt.cls));
color.setAlpha(200 * pt.confidence);
sketch.noStroke();
sketch.fill(color);
sketch.rectMode(sketch.CENTER);
sketch.rect(pt.x, pt.y, width/meshSize-1, height/meshSize-1);
});
}
Insert cell
// loss = {
// let loss = [];
// let newLoss = () => {loss.push(d3.mean(data)); return loss;}
// while (false) {
// yield Promises.delay(1000, newLoss());
// }
// }
Insert cell
{
while (true) {
yield Promises.delay(100, model.fit(inputs(), outputs(), { epochs: 1 }));
}
}
Insert cell
{
while (true) {
yield Promises.delay(150, predict());
}
}
Insert cell
addPoint = (sketch) => {
data.push(new Object({ x: sketch.mouseX, y: sketch.mouseY, cls: clsContainer.cls }));
}
Insert cell
model = {
const input = tf.input({ shape: [2] });
const dense1 = tf.layers.dense({ units: 3, activation: "tanh" }).apply(input);
const dense2 = tf.layers.dense({ units: 3, activation: "tanh" }).apply(dense1);
const output = tf.layers.dense({ units: 1}).apply(dense2);
const model = tf.model({ inputs: input, outputs: output });
model.compile({ loss: "meanSquaredError", optimizer: "sgd" });
return model;
}
Insert cell
inputs = () => {
return tf.tensor2d(
data.flatMap((pt) => [pt.x, pt.y]),
[data.length, 2]
);
}
Insert cell
outputs = () => {
return tf.tensor2d(
data.map((pt) => pt.cls == "a" ? 1 : 0),
[data.length, 1]
);
}
Insert cell
predict = () => {
mesh.map((pt) => {
let prediction = model
.predict(tf.tensor2d([pt.x, pt.y], [1, 2]))
.arraySync()[0][0];
pt.cls = prediction > 0.5 ? "a" : "b";
pt.confidence =
prediction > 0.5 ? 2 * (prediction - 0.5) : 2 * (0.5 - prediction);
});
}
Insert cell
Insert cell
colors = new Map([
["a", d3.schemeSet1[0]],
["b", d3.schemeSet1[1]]
])
Insert cell
import {p5} from "@makio135/p5"
Insert cell
tf = require('@tensorflow/tfjs')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more