Getting the result into a variable

人走茶凉 提交于 2019-12-01 23:28:38

I found the answer to be:

    answer.data().then((d)=>{
      console.log(d[0])
    })

answer has a data method which returns a promise. You can get the data from the promise.

I searched stackoverflow which lead me to this question: Get data from 2D tensor with tensorflow js

Rocksetta kindly posted a link to their code on the following site:

https://hpssjellis.github.io/beginner-tensorflowjs-examples-in-javascript/beginner-examples/tfjs02-basics.html

The easiest way is to use answer.dataSync(), but it will block the main thread. If you are comfortable with async / await, answer.data() is the solution.

Sometimes

The easiest way is to use answer.dataSync(), but it will block the main thread. If you are comfortable with async / await, answer.data() is the solution.

works fine but other times

answer.dataSync()

returns an array. When faced with the array then you need to try

answer.dataSync()[0]

or some other array number. Same issue with

await answer.data()[0]

To get the value of a Tensor into normal JavaScript variable, one can use two built-in functions of TensorflowJs: one is synchronous dataSync() and the other is asynchronous data().

dataSync() will block the UI thread. So whenever possible the asynchronous data() should be preferred.

const x = tf.tensor1d([45, 48]);
x.print();
/* Async way */
(async () => {
  const val = await x.data()
   // get the first element
  console.log(val[0])
})()
/* Sync way */
const val = x.dataSync()[0]
console.log(val)
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
  </head>

  <body>
  </body>
</html>

Here's my favorite way:

var answerdata = await answer.data()
var answerArray = Array.from(answerdata);

answerArray will be flattened, but it's fast and simple. You're usually in an async function anyways if you're loading a Keras model or doing a variety of other async things.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!