Skip to content

Instantly share code, notes, and snippets.

@kedevked
Created March 14, 2019 02:32
Show Gist options
  • Save kedevked/c8a1a7f2f380ed8f18865ad726a0f5df to your computer and use it in GitHub Desktop.
Save kedevked/c8a1a7f2f380ed8f18865ad726a0f5df to your computer and use it in GitHub Desktop.
use tensorflow.js in a web worker
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.14.2/dist/tf.min.js"></script>
<script>
const worker_function = () => {
onmessage = () => {
console.log('from web worker')
this.window = this
importScripts('https://cdn.jsdelivr.net/npm/setimmediate@1.0.5/setImmediate.min.js')
importScripts('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.10.3')
tf.setBackend('cpu')
const res = tf.zeros([1, 2]).add(tf.ones([1, 2]))
res.print()
postMessage({res: res.dataSync(), shape: res.shape})
};
}
if (window != self)
worker_function();
</script>
<script>
const worker = new Worker(URL.createObjectURL(new Blob(["(" + worker_function.toString() + ")()"], { type: 'text/javascript' })));
worker.postMessage({});
worker.onmessage = (message) => {
console.log('from main thread')
const {data} = message
tf.tensor(data.res, data.shape).print()
}
</script>
</head>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment