使用tensorflow js从2D张量获取数据 [英] Get data from 2D tensor with tensorflow js
问题描述
我想通过 tensorflow.js 从2D张量中获取数据。我尝试使用 data()
方法,如下所示:
I would like to get the data from a 2D tensor with tensorflow.js. I tried to use the data()
method like this:
const X = tf.tensor2d([1, 2, 3, 4], [2, 2, 5, 3]);
X.data().then(X => console.log(X)};
但结果是一个扁平的1D数组:
But the result is a flatten 1D array:
Float32Array(8) [1, 2, 3, 4, 2, 2, 5, 3]
有没有办法保持阵列的形状?
Is there a way to keep the shape of the array?
推荐答案
为了提高速度,Tensor中的数据总是被平铺为类型1维数组。
Data in the Tensor is always stored flattened as types 1 dimensional array, for speed.
你给出的例子不起作用,因为 tensor2d
的第二个参数是 shape
。工作你需要包装另一个数组:
The example you gave will not work, because 2nd parameter to tensor2d
is shape
. To make it work you either need to wrap it another array:
const x = tf.tensor2d([[1, 2, 3, 4], [2, 2, 5, 3]]); //shape inferred as [2, 4]
或者你可以明确地提供形状:
or you could explicitly provide shape:
const x = tf.tensor2d([1, 2, 3, 4, 2, 2, 5, 3], [2, 4]); // shape explicitly passed
正如您所建议的,当您检查数据时,您将始终获得一维数组,无论原始形状如何
as you suggested though, when you inspect data you will always get 1 dimensional array, regardless of original shape
await x.data() // Float32Array(8) [1, 2, 3, 4, 2, 2, 5, 3]
x.shape // [2, 4]
但是如果你 print()
你的张量,形状会被考虑在内,它会显示为
if however you print()
your tensor, shape is taken into account and it will appear as
Tensor
[[1, 2, 3, 4],
[2, 2, 5, 3]]
这篇关于使用tensorflow js从2D张量获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!