Public
Edited
Dec 11, 2022
Fork of Blog Post
2 forks
Insert cell
Insert cell
data_to_me@2.csv
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
features = Object.keys(data[0]).slice(18, 31)
Insert cell
// viewof selectedFeatures = Inputs.checkbox(features, {label: "Features", value: features.slice(0, 3)})
Insert cell
outcomes = Object.keys(data[0]).slice(0, 17)
Insert cell
viewof selectedPredictions = Inputs.checkbox(outcomes, {label: "Outcomes", value: outcomes.slice(0, 3)})
Insert cell
selectedPredictions
Insert cell
selectedPredictionsIndices = selectedPredictions.map(e => outcomes.indexOf(e))
Insert cell
data = data_to_me
Insert cell
OUTPUT_OBJECTS = data.map(e => Object.fromEntries(Object.entries(e).slice(0,17)))
Insert cell
// INPUTS_OBJECTS.map(e => Object.values(e))
Insert cell
outputs_raw = OUTPUT_OBJECTS.map(e => Object.values(e))
Insert cell
outputs = tf.tensor(OUTPUT_OBJECTS.map(e => Object.values(e)))
Insert cell
Insert cell
INPUT_OBJECTS = data.map(e => Object.fromEntries(Object.entries(e).slice(18,31)))
Insert cell
// INPUT_OBJECTS = data.map(e => subset(e, selectedFeatures))
Insert cell
inputs_raw = INPUT_OBJECTS.map(e => Object.values(e))
Insert cell
inputs = tf.tensor(INPUT_OBJECTS.map(e => Object.values(e)))
Insert cell
inputs.shape
Insert cell
viewof activation1 = Inputs.radio(["sigmoid", "tanh"], {label: "First layter activation", value: "sigmoid"})
Insert cell
// viewof learningRate1 = slider({
// min: 0,
// max: 0.1,
// step: 0.001,
// precision: 3,
// value: 0.005,
// title: "Learning Rate",
// description: ""
// })
Insert cell
viewof learningRate1 = Inputs.range([0, 0.1], {label: "Learning Rate", step: 0.001, value: "0.005"})
Insert cell
viewof epoch = Inputs.range([0, 30], {label: "Epoch", step: 1, value: "10"})
Insert cell
// viewof epoch = slider({
// min: 0,
// max: 30,
// step: 1,
// value: 10,
// title: "Epoch",
// description: ""
// })
Insert cell
model = {
// https://towardsdatascience.com/build-a-simple-neural-network-with-tensorflow-js-d434a30fcb8
const model = tf.sequential();
model.add(
tf.layers.dense({
inputShape: [inputs.shape[1]],
units: 3,
activation: activation1
})
);

model.add(
tf.layers.dense({
units: outputs.shape[1],
activation: "softmax"
})
);

model.compile({
optimizer: tf.train.sgd(learningRate1),
loss: "meanSquaredError",
metrics: ["mse"]
});
return model;
}
Insert cell
loss
Insert cell
width = 1000
Insert cell
// lossplot = html`
// <div style=width:${width}; display: flex; flex-direction: row;'>
// <div id='lossPlot' style='display:flex; flex: 0.5;' />
// </div>
// `
Insert cell
trainLossPlot = html`
<div id='lossPlot'></div>
`
Insert cell
Insert cell
Insert cell
onStartTraining = async () => {
const interval = 40;
await training({
callback: ({ model, epoch, logs }) => {
loss[epoch] = logs.loss;

updateLossPlot({ loss });
}
});
}
Insert cell
loss = []
Insert cell
training = async ({ callback }) => {
await model.fit(inputs, outputs, {
shuffle: true,
epochs: epoch,
callbacks: {
onEpochEnd: async (epoch, logs) => {
callback({ model, epoch, logs });
await tf.nextFrame();
}
}
});
}
Insert cell
Insert cell
selectedPredictions
Insert cell
Insert cell
viewof predButton = html`<form>${Object.assign(html`<button type=button>Predict`, {onclick: event => event.currentTarget.dispatchEvent(new CustomEvent("input", {bubbles: true}))})}`
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
viewof colorBy = Inputs.select(attribs, { label: "color by" })
Insert cell
viewof numberTicks = Inputs.range([0, 10], {label: "Number of Ticks", step: 1, value: "3"})
Insert cell
Insert cell
Insert cell
parallelPlot = Plot.plot({
marginLeft: 250,
marginRight: 20,
height: 300,
x: {
axis: null
},
y: {
padding: 0.1,
domain: attribs,
label: null,
tickPadding: 9
},
color: {
type: "categorical",
scheme: schemec,
legend: true,
},
marks: [
Plot.ruleY(attribs),
Plot.line(parallelData, {
...xy,
z: "model",
stroke: (d) => d.datum.model,
strokeWidth: 2.9,
strokeOpacity: 0.9
}),
Plot.text(ticks, {
...xy,
text: "value",
fill: "black",
stroke: "white",
strokeWidth: 3
})
]
})
Insert cell
// chart = {
// // Source: https://observablehq.com/@vega/vega-lite-parallel-coordinates
// const height = 200;
// const hover = vl
// .selectSingle()
// .on("mouseover")
// .nearest(true)
// .empty("none");

// const base = vl.markRule({ color: "#ccc" }).encode(
// vl.x().fieldN("key"),
// vl.detail().count()
// );

// const line = base.markLine().encode(
// vl.color().fieldN("model"),
// vl.detail().fieldN("index"),
// vl.opacity().if(hover, vl.value(1)).value(0.6),
// vl.y().fieldQ("norm_val").axis(null),
// vl.tooltip(attribs)
// );

// const points = line.markCircle()
// .select(hover)
// .encode(vl.size().if(hover, vl.value(50)).value(5));

// // Generates a spec to show tick values at an specific value of y0
// const tick = y0 =>
// vl.layer(
// base.markText({ style: "label" }).encode(vl.text().max("max")),
// base.markTick({ style: "tick", size: 8, color: "#ccc" })
// )
// .encode(vl.y().value(y0));

// // Create an array with *numTicks* ticks
// const ticks = Array.from({ length: numTicks })
// .map((_, i) => tick((height / (numTicks - 1)) * i));

// return vl
// .layer(base, line, points, ...ticks)
// .data(dataForPlot)
// .transform(
// vl.filter(attribs.map(a => `datum["${a}"] != null`).join(" && ")),
// vl.window(vl.count().as("index")),
// vl.fold(attribs),
// vl.groupby("key").joinaggregate(vl.min("value").as("min"), vl.max("value").as("max")),
// vl.calculate("(datum.value - datum.min) / (datum.max - datum.min)").as("norm_val"),
// vl.calculate("(datum.min + datum.max) / 2").as("mid")
// )
// .config({
// axisX: { domain: false, labelAngle: 0, tickColor: "#ccc", title: null },
// view: { stroke: null },
// style: {
// label: { baseline: "middle", align: "right", dx: -5 },
// tick: { orient: "horizontal" }
// }
// })
// .width(width - 100)
// .height(height)
// .render();
// }
Insert cell
tf = require("@tensorflow/tfjs@0.8.0/dist/tf.min.js")
Insert cell
import {vl} from "@vega/vega-lite-api"
Insert cell
tfvis = require('https://bundle.run/@tensorflow/tfjs-vis@0.1.1')
Insert cell
import {slider} from "@jashkenas/inputs"
Insert cell
Plotly = require('plotly.js-dist')
Insert cell
// import {button} from "@jashkenas/inputs"
Insert cell
d3 = require("d3@6")
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