Published unlisted
Edited
Insert cell
# An Interactive Introduction to TensorFlow.js
https://observablehq.com/@zaidalyafeai/an-intractive-introduction-to-tensorflow-js
Insert cell
tf = require('@tensorflow/tfjs@0.8.0')
Insert cell
import {show} from "@zaidalyafeai/show-tensor"
Insert cell
show(tf.scalar(3))
Insert cell
show(tf.tensor([2,2]))
Insert cell
show(tf.zeros([2,2]))
Insert cell
show(tf.tensor([2,3,4]).square())
Insert cell
show(tf.tensor([1,2,3]).square().square())
Insert cell
{
let x = tf.tensor([1,2,3]);
x.dispose()
return x
}
Insert cell
function f(x)
{
return tf.tidy(()=>{
const y = x.square();
const z = x.mul(y);
return z
});
}
Insert cell
model = {
//create a sequential method
const model = tf.sequential();
//add frist conv layer
model.add(tf.layers.conv2d({
inputShape: [28, 28, 1],
kernelSize: 5,
filters: 8,
strides: 1,
activation: "relu",
kernelInitializer: "VarianceScaling"
}));
//add first pooling layer
model.add(tf.layers.maxPooling2d({
poolSize: [2, 2],
strides: [2, 2]
}));

//add second conv layer
model.add(tf.layers.conv2d({
kernelSize: 5,
filters: 16,
strides: 1,
activation: "relu",
kernelInitializer: "VarianceScaling"
}));
//add the second pooloing layer
model.add(tf.layers.maxPooling2d({
poolSize: [2, 2],
strides: [2, 2]
}));

//flatten the model to prepare the input for the dense layer
model.add(tf.layers.flatten());

//a dense layer with output equals the number of classes
model.add(tf.layers.dense({
units: 10,
kernelInitializer: "VarianceScaling",
activation: "softmax"
}));
//compile the model using and adam optimizer
await model.compile({
optimizer: tf.train.adam(0.0001),
loss: "categoricalCrossentropy",
metrics: ["accuracy"]
});
//return the model
return model;
}
Insert cell
function createBatch(BATCH_SIZE)
{
let input = tf.zeros([BATCH_SIZE,28,28,1]);
let labels = tf.oneHot(tf.zeros([BATCH_SIZE]),10)
return [input , labels]
}
Insert cell
batch = createBatch(5)
Insert cell
batch[0].shape
Insert cell
show(batch[1])
Insert cell
h = await model.fit(batch[0], batch[1],
{
batchSize: 10,
epochs: 1
})
Insert cell
show(model.predict(tf.zeros([1, 28, 28, 1])))
Insert cell
loss = h.history.loss[0]
Insert cell
accuracy = h.history.acc[0]
Insert cell
mobilenet = await tf.loadModel('https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json')
Insert cell
mobilenet.inputs[0].shape
Insert cell
import {IMAGENET_CLASSES} from "@zaidalyafeai/imagenet-classes"
Insert cell
img = {
let img = new Image();
img.crossOrigin = '*';
img.src = 'https://i.imgur.com/p2mewNT.jpg';
img.width = 224;
img.height = 224;
return img;
}
Insert cell
function preprocess(img)
{
let tensor = tf.fromPixels(img).toFloat();

const offset = tf.scalar(127.5);
// Normalize the image
const normalized = tensor.sub(offset).div(offset);
//We add a dimension to get a batch shape [1,224,224,3]
const batched = normalized.expandDims(0)
return batched
}
Insert cell
preImg = preprocess(img)
Insert cell
function predict(input)
{
//get predictions
let pred = mobilenet.predict(input);
//retreive the highest probability class label
let idx = pred.argMax().buffer().values[0];
return idx
}
Insert cell
cls = predict(preImg)
Insert cell
IMAGENET_CLASSES[cls]
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more