如何从2D张量获取数据?

问题描述 投票:4回答:3

我想用tensorflow.js从2D张量获取数据。我试图像这样使用data()方法:

const X = tf.tensor2d([[1, 2, 3, 4], [2, 2, 5, 3]]);
X.data().then(X => console.log(X)};

但是结果是一个扁平的一维数组:

Float32Array(8) [1, 2, 3, 4, 2, 2, 5, 3]

有没有办法保持阵列的形状?

javascript tensorflow.js
3个回答
0
投票

为了速度,Tensor中的数据始终被展平为类型1维数组。

您提供的示例将不起作用,因为tensor2d的第二个参数是shape。要使其工作,您需要将其包装另一个数组:

const x = tf.tensor2d([[1, 2, 3, 4], [2, 2, 5, 3]]); //shape inferred as [2, 4]

或者您可以显式提供形状:

const x = tf.tensor2d([1, 2, 3, 4, 2, 2, 5, 3], [2, 4]); // shape explicitly passed

但是正如您所建议的那样,当检查数据时,无论原始形状如何,您将始终获得一维数组

await x.data() // Float32Array(8) [1, 2, 3, 4, 2, 2, 5, 3]
x.shape // [2, 4]

但是如果您print()张量,则考虑到形状,它将显示为

Tensor
    [[1, 2, 3, 4],
     [2, 2, 5, 3]]

0
投票

我使用函数在网页上显示2D张量

async function myTensorTable(myDiv, myOutTensor, myCols, myTitle){   

 document.getElementById(myDiv).innerHTML += myTitle + '<br>'
 const myOutput = await myOutTensor.data()
 myTemp = '<table border=3><tr>'
   for (myCount = 0;    myCount <= myOutTensor.size - 1;   myCount++){   
     myTemp += '<td>'+ myOutput[myCount] + '</td>'
     if (myCount % myCols == myCols-1){
         myTemp += '</tr><tr>'
     }
   }   
   myTemp += '</tr></table>'
   document.getElementById(myDiv).innerHTML += myTemp + '<br>'
}

]的使用示例>

https://hpssjellis.github.io/beginner-tensorflowjs-examples-in-javascript/beginner-examples/tfjs02-basics.html


0
投票

您可以在张量对象上使用arraySync方法。它返回与synchronously

© www.soinside.com 2019 - 2024. All rights reserved.