【发布时间】:2018-08-14 19:15:51
【问题描述】:
我有一个二维张量,我想获取索引 i,j 值的元素的值。
【问题讨论】:
标签: tensorflow.js
我有一个二维张量,我想获取索引 i,j 值的元素的值。
【问题讨论】:
标签: tensorflow.js
有很多方法可以检索 tensor2d 的元素 [i,j] 的值
考虑以下几点:
使用 slice 直接检索从坐标 [i, j] 开始的 tensor2d,大小为 [1, 1]
h.slice([i, j], 1).as1D().print()
使用gather 获取第i 行作为张量2d,然后使用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 变量(数字类型),那么您将需要 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>
【讨论】:
您可以使用.dataSync() 或者如果您可以等待.data() 来检索包含张量的所有值的一维数组。
现在我们只需要使用以下公式从二维坐标计算一维索引:
索引 = 行长 * 行数 + 列数
以下代码显示了如何使用每个版本。
注意异步方法中的async 和await:async 使函数异步,所以我们可以使用await 等待另一个promise 解决(.data() retuns a promise) .因为异步函数会返回一个 Promise,所以我们必须在使用 .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>
【讨论】: