如何获取张量的元素i,j的值

How to get the value of the element i, j of a tensor

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

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

考虑以下因素:

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

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] 以便在其他张量计算中使用它,例如 divide/multiply 元素矩阵,则需要将元素转换为标量。

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

如果你想return那个值到javascript变量(数字类型),那么你需要dataSync() or data() as described in this

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>

您可以使用 .dataSync() or if you can wait for it .data() 检索包含张量所有值的一维数组。

现在我们只需使用以下公式从二维坐标计算一维索引:

index = rowlength * rownumber + columnnumber

以下代码展示了各个版本的使用方法。

注意异步方法中的asyncawaitasync使函数异步,所以我们可以使用await等待另一个要解决的承诺(.data() 重新承诺)。因为异步函数 returns 一个承诺,我们必须在使用 .then()

记录它之前等待它

function getValSync(t, i, j) {
  const data = t.dataSync();
  return data[t.shape[0] * j + i]; //Or *i+j, depending on what the dimension order is
}

async function getValAsync(t, i, j) {
  const data = await t.data();
  return data[t.shape[0] * j + i];
}

const t2d = tf.tensor2d([1, 2, 3, 4], [2, 2]);

t2d.print();

console.log("1,0:", getValSync(t2d, 1, 0));
console.log("1,1:", getValSync(t2d, 1, 1));

getValAsync(t2d, 0, 0).then(v => console.log("0,0:", v));
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0">
</script>