Published
Edited
Sep 14, 2022
3 stars
Insert cell
Insert cell
ml = require("https://www.lactame.com/lib/ml/2.2.0/ml.min.js")
Insert cell
KNN = ml.SL.KNN.default
Insert cell
dataset = require("@observablehq/iris")
Insert cell
data = dataset.map(d => [
d.sepalLength,
d.sepalWidth,
d.petalLength,
d.petalWidth
])
Insert cell
labels = dataset.map(d => d.species)
Insert cell
Insert cell
// A function to select at random n out of the 150 data points as training set
pick = {
const p = Array.from({ length: dataset.length }).fill(false);
for (let i = 0; i < learn_samples; i++) p[i] = true;
p.sort(_ => Math.random() - 1 / 2);
return function(d, i) {
return p[i];
};
}
Insert cell
predict = new KNN(data.filter(pick), labels.filter(pick), {
// distance: …,
k: 5
})
Insert cell
predict.predict([3.3, 2.3, 4, 1.5])
Insert cell
error_rate =
data
.map((d, i) => predict.predict(d) !== labels[i])
.reduce((a, b) => a + b, 0) / data.length
Insert cell
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