Published
Edited
Jun 30, 2020
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
dl = require("datalib")
Insert cell
data = dl.csv("https://vega.github.io/vega-datasets/data/gapminder-health-income.csv")
Insert cell
Insert cell
table(data, { title: "Gapminder" })
Insert cell
Insert cell
vegalite({
data: { values: data },
width: 400,
height: 300,
mark: "circle",
encoding: {
x: { field: "income", type: "Q" },
y: { field: "health", type: "Q", scale: { domain: [45, 90] } }
//size: { field: "population", type: "Q" }
},
config: {
circle: { color: "#1E4865", size: 40, opacity: 0.6 }
}
})
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
tf = require("@tensorflow/tfjs@2.0.1")
Insert cell
tensors = {
// Wrapping these calculations in a tidy will dispose any
// intermediate tensors.

return tf.tidy(() => {
// Step 1. Shuffle the data
tf.util.shuffle(data);

// Step 2. Convert data to Tensor
const inputs = data.map(d => d.income);
const labels = data.map(d => d.health);

const inputTensor = tf.tensor2d(inputs, [inputs.length, 1]);
const labelTensor = tf.tensor2d(labels, [labels.length, 1]);

//Step 3. Normalize the data to the range 0 - 1 using min-max scaling
const inputMax = inputTensor.max();
const inputMin = inputTensor.min();
const labelMax = labelTensor.max();
const labelMin = labelTensor.min();

const normalizedInputs = inputTensor
.sub(inputMin)
.div(inputMax.sub(inputMin));
const normalizedLabels = labelTensor
.sub(labelMin)
.div(labelMax.sub(labelMin));

return {
inputs: normalizedInputs,
labels: normalizedLabels,
// Return the min/max bounds so we can use them later.
inputMax,
inputMin,
labelMax,
labelMin
};
});
}
Insert cell
Insert cell
tensors.inputs.shape
Insert cell
tensors.inputs.toString()
Insert cell
// Loss: Mean Squared Error (MSE)
loss = (predictions, labels) => {
return tf.tidy(() =>
predictions.sub(labels)
.square()
.mean()
);
}
Insert cell
Insert cell
Insert cell
inputs = tensors.inputs
Insert cell
labels = tensors.labels
Insert cell
Insert cell
mutable nodes = 5
Insert cell
Insert cell
model = {
// Create a sequential model
const model = tf.sequential();

// Add a single input layer
model.add(
tf.layers.dense({
inputShape: [1],
units: 5,
activation: "relu",
useBias: true
})
);

// // Add a single input layer
// model.add(tf.layers.dense({inputShape: [1], units: 1, useBias: true}));

// Add an output layer
model.add(tf.layers.dense({ units: 1, useBias: true }));

// Compile the model
await model.compile({
optimizer: tf.train.adam(),
loss: tf.losses.meanSquaredError,
metrics: ["mse"]
});

return model;
}
Insert cell
Insert cell
train = {
const batchSize = 8;
const epochs = 50;

return await model.fit(inputs, labels, {
batchSize,
epochs,
shuffle: true
});
}
Insert cell
Insert cell
predictions.data()
Insert cell
predictions = {
train; // Just to subscribe changes in training info
const predictions = tf.tidy(() => {
const normalizedPred = model.predict(inputs);

return normalizedPred
.mul(tensors.labelMax.sub(tensors.labelMin))
.add(tensors.labelMin);
});
yield predictions;

try {
yield invalidation;
} finally {
predictions.dispose();
}
}
Insert cell
Insert cell
Insert cell
table(dataOutput, { title: "Gapminder" })
Insert cell
vegalite({
width: 400,
height: 300,
data: { values: dataOutput },
layer: [
{
mark: "point",
encoding: {
x: {
field: "income",
type: "quantitative",
scale: { type: "log" }
//axis: { title: "log (income)" }
},
y: {
field: "health",
type: "quantitative",
scale: { domain: [45, 90] }
}
}
},
{
mark: { type: "circle", clip: true },
encoding: {
x: { field: "income", type: "quantitative" },
y: {
field: "pred_health",
type: "quantitative",
scale: { zero: false }
}
}
}
],
config: {
circle: { color: "#1E4865", size: 40, opacity: 0.6 },
line: { color: "#F1AD46", strokeWidth: 4, opacity: 0.6 }
}
})
Insert cell
Insert cell
dataUrl = "https://raw.githubusercontent.com/vega/vega-datasets/gh-pages/data/gapminder-health-income.csv"
Insert cell
vegalite = require("vega-embed")
Insert cell
Insert cell
Insert cell
import {table} from "@tmcw/tables/2"
Insert cell
import {slider} from "@jashkenas/inputs"
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