【问题标题】:Get the value of an item in a tensor in Tensorflow.js在 Tensorflow.js 中获取张量中项目的值
【发布时间】:2018-09-26 21:37:28
【问题描述】:

在指定索引后,如何从 Tensorflow.js 中的张量中获取值?

【问题讨论】:

    标签: indexing tensor tensorflow.js


    【解决方案1】:
    const newTensor = tf.tensor2d([[2,4], [5,6]])
    newTensor.get([0]) ##returns 2
    newTensor.get([3]) ##returns 6
    

    谢天谢地,所有这些都返回一个数字而不是张量。

    【讨论】:

    • 不起作用:错误:get() 中的坐标数必须与张量的秩匹配
    • @JavaRunner 你能分享它不能使用的代码/张量吗?
    • 这个get函数在最新版本中不再存在。
    【解决方案2】:

    您可以为此使用数据同步。

    const newTensor = tf.tensor2d([[2,4],[5,6]]);
    const tensorData = newTensor.dataSync();
    console.log("data[0] is " + tensorData[0]);
    console.log("data[3] is " + tensorData[3]);
    

    https://codepen.io/anon/pen/NMKgeO?editors=1011

    【讨论】:

      【解决方案3】:

      您可以使用以下更强大的方法

      tensor.buffer().get(0, 0);

      这将允许您索引张量的逻辑坐标(二维坐标,而不是扁平的一维坐标)。见link

      【讨论】:

      • 你会如何在 python Tensorflow Keras 中做到这一点?
      【解决方案4】:

      tf.Tensor.dataSync() 不保留原始形状。如果您想保留形状,可以使用tf.Tensor.arraySync()

      【讨论】:

        【解决方案5】:

        或者你也可以使用 slice 来获取值:

        let value = tensor.slice([i,j], [1, 1]);
        

        let value = tensor.slice([i,j], [1, 1]).arraySync()[0][0];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-12
          • 1970-01-01
          • 2019-11-28
          • 1970-01-01
          • 2022-10-23
          • 2020-01-03
          相关资源
          最近更新 更多