gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:15:29 25 4
gpt4 key购买 nike

我有一个二维张量,我想获得索引 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com