tensorflow.js - 如何获取张量的元素 i, j 的值

标签 tensorflow.js

我有一个二维张量,我想获得索引 i,j 值的元素的值。

最佳答案

有很多方法可以检索 tensor2d 的元素 [i,j] 的值

考虑以下:

使用 slice直接检索从坐标 [i, j] 开始的 tensor2d,其大小为 [1, 1]

h.slice([i, j], 1).as1D().print()

使用 gather 将行 i 作为 tensor2d 获取然后是带有 slice 的元素 j
h.gather(tf.tensor1d([i], 'int32')).slice([0, j], [1, 1]).as1D().print()

使用 stack将行 i 检索为 tensor1d 和 slice检索所需的元素
h.unstack()[i].slice([j], [1]).print()

const h = tf.tensor2d([45, 48, 45, 54, 5, 7, 8, 10, 54], [3, 3]);
// get the element of index [1, 2]
h.print()
h.gather(tf.tensor1d([1], 'int32')).slice([0, 2], [1, 1]).as1D().print()
h.slice([1, 2], 1).as1D().print()
h.unstack()[1].slice([2], [1]).print()
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>
  </head>

  <body>
  </body>
</html>


如果目标是获取元素 [i, j] 以便在其他张量计算中使用它,例如将矩阵除以/乘以元素,则需要将元素转换为标量。
h.slice([i, j], 1).as1D().asScalar()

如果你想将该值返回给一个 javascript 变量(类型为 number),那么你将需要 dataSync()data()如本 answer 中所述

h.slice([i, j], 1).as1D().dataSync()[0]
// or
const data = await h.slice([i, j], 1).as1D().data()

const h = tf.tensor2d([45, 48, 45, 54, 5, 7, 8, 10, 54], [3, 3]);
// get the element of index [1, 2]
h.print()
// sync method
const val = h.unstack()[1].slice([2], [1]).dataSync()
console.log(val[0]);
// async method
(async () => {
  const val = await h.slice([1, 2], 1).as1D().data()
  console.log(val[0])
})()
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
  </head>

  <body>
  </body>
</html>

关于tensorflow.js - 如何获取张量的元素 i, j 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51848367/

相关文章:

javascript - TensorFlow JS 中的单位和输入形状

tensorflow - TensorFlow Universal Sentence Encoder Lite 嵌入的范围有限?

python - 如何将 Tensorflow 模型转换为 tensorflow.js 模型?

javascript - tf.browser.fromPixels() 不工作因为 "DOM is not ready yet"

javascript - 将视频流 JavaScript 代码传输到 React (ML5)

javascript - 如何使用keras/tensorflow将tfjs模型加载到python中

javascript - Tensorflow.js 中的图像大小调整方法(resizeBilinear 和 resizeNearestNeighbor)不会返回正确的结果

node.js - 我是否必须重新安装 CUDA 9.0 才能使用 tfjs-node-gpu?

javascript - 将 python TensorFlow Layers 模型加载到 JavaScript 中

machine-learning - 在tensorflow.js中将预测值Y获取到一定数量的X值