Published
Edited
Jul 12, 2019
Insert cell
Insert cell
Insert cell
viewof imgSrc = {
// Hint: imgur.com has relaxed CORS policies.
const catSrc = 'https://raw.githubusercontent.com/tensorflow/tfjs-examples/master/mobilenet/cat.jpg';
const input = html`<input type=text style='width:600px; height: 20px; font-size: 14px'>`;
input.value = catSrc;
return input;
}
Insert cell
Insert cell
viewof webcam = html`<input type=checkbox value=1>`
Insert cell
source = {
if (webcam) {
const vid = html`<video autoplay="true" id="vid" width=224 height=224></video>`;
navigator.getUserMedia({video: true}, (stream) => {
vid.src = window.URL.createObjectURL(stream);
}, ()=>{});
return vid;
} else {
const img = new Image();
img.setAttribute('crossorigin', 'anonymous');
img.width = 224;
img.height = 224;
img.src = imgSrc;
return img;
}
}
Insert cell
Insert cell
tf = require('@tensorflow/tfjs@0.10.3')
Insert cell
model = await tf.loadModel('https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json')
Insert cell
Insert cell
logits = {
while(true) {
yield tf.tidy(() => {
let offset = tf.scalar(127.5)
let img = tf.fromPixels(source)
let inputs = img.cast('float32').sub(offset).div(offset).reshape([1, 224, 224, 3])
return model.predict(inputs).dataSync()
})
}
}
Insert cell
maxProb = Math.max.apply(null, logits)
Insert cell
topClass = IMAGENET_CLASSES[logits.indexOf(maxProb)]
Insert cell
Insert cell
topTen = _.zip(logits, IMAGENET_CLASSES)
.sort((a, b)=> b[0] - a[0])
.filter((v, i) => i < 10)
.map(a => { return { rel : a[0], text : a[1] }; })
Insert cell
viewof view = {
let result = embed({
data : { values : topTen },
encoding : {
y : { field : 'text', type : 'ordinal', sort : 'rel', axis : { labels : false } }
},
layer : [ {
mark : { type : 'bar', color : '#ffbf79' },
encoding : {
x : { field : 'rel', type : 'quantitative', scale : { domain : [ 0, 1 ] } }
}
}, {
mark : {
type : 'text',
align : 'left',
baseline : 'middle'
},
encoding : {
text : { field : 'text', type : 'nominal' },
x : { value : 10 }
}
}
],
width : 600
});
return result;
}
Insert cell
_ = require('underscore')
Insert cell
embed = require('vega-embed@3')
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