Created
March 14, 2019 02:32
-
-
Save kedevked/c8a1a7f2f380ed8f18865ad726a0f5df to your computer and use it in GitHub Desktop.
use tensorflow.js in a web worker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<head> | |
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script> | |
<script> | |
const worker_function = () => { | |
onmessage = () => { | |
console.log('from web worker') | |
this.window = this | |
importScripts('https://cdn.jsdelivr.net/npm/[email protected]/setImmediate.min.js') | |
importScripts('https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]') | |
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