Published
Edited
Jun 7, 2022
Insert cell
# Tensorflow JS Example

via [https://medium.com/geekculture/machine-learning-modeling-or-xor-with-tensorflowjs-d9c03c5bd17e](https://medium.com/geekculture/machine-learning-modeling-or-xor-with-tensorflowjs-d9c03c5bd17e)
Insert cell
model = tf.sequential();
Insert cell
input = [[0, 0], [1, 0], [0, 1], [1, 1]];
Insert cell
inputTensor = tf.tensor(input, [input.length, 2]);
Insert cell
lossHistory = []
Insert cell
initModel = function*(model) {
lossHistory.length = 0
const output = [[0], [1], [1], [0]]
const outputTensor = tf.tensor(output, [output.length, 1]);
//input + 1 hidden layer
model.add(
tf.layers.dense({
inputShape: [2],
units: 2,
activation: 'sigmoid'
})
);
//output
model.add(
tf.layers.dense({
units: 1,
activation: 'sigmoid'
})
)
model.compile({
optimizer: tf.train.adam(0.1),
loss: 'meanSquaredError'
});
yield "training..."
model.fit(inputTensor, outputTensor, {
epochs: 1000,
shuffle: true,
callbacks: {
onEpochEnd: async (epoch, { loss }) => {
lossHistory.push(loss)
//await new Promises.delay(100)
// any actions on during any epoch of training
//await tf.nextFrame();
}
}
})
yield model
return model
}
Insert cell
{
for(let step of initModel(model)){
yield step ?? '?'
}
}
Insert cell
prediction = model?.predict(inputTensor)?.arraySync() ?? []
Insert cell
sparkline(lossHistory,800,200)
Insert cell
tf = import("https://cdn.skypack.dev/@tensorflow/tfjs@2")
Insert cell
import {sparkline} from "d4d66ef8e0b4d4f4"
Insert cell
useState = React.useState
Insert cell
import {React} from "@hastebrot/react@356"
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