首页 > 解决方案 > tf.dataSync() 不会以可读形式从 BlazeFaceModel 返回张量

问题描述

我正在使用 BlazeFaceModel 检测人脸,然后再使用 Tensorflow.js 将人脸发送到另一个模型

当我使用自定义模型并尝试获取张量输出时,我使用了下面的代码,它可以返回张量。

    const returnTensors = true;
    const faces = await blazeModel.estimateFaces(tensor, returnTensors);
    if (faces !== null) {
      // Download the tensors to view the shape
      const face = faces.dataSync();
      face.forEach((pred, i) => {
        console.log(`x: ${i}, pred: ${pred}`);
      });
    }

但是在应用 BlazeFaceModel 的张量输出时会引发以下错误:

faces.dataSync is not a function. (In 'faces.dataSync()', 'faces.dataSync' is undefined)

来自 console.log(faces) 的输出

Array [
  Object {
    "bottomRight": Tensor {
      "dataId": Object {},
      "dtype": "float32",
      "id": 60793,
      "isDisposedInternal": false,
      "kept": false,
      "rankType": "1",
      "scopeId": 116528,
      "shape": Array [
        2,
      ],
      "size": 2,
      "strides": Array [],
    },
    "landmarks": Tensor {
      "dataId": Object {},
      "dtype": "float32",
      "id": 60795,
      "isDisposedInternal": false,
      "kept": false,
      "rankType": "2",
      "scopeId": 116532,
      "shape": Array [
        6,
        2,
      ],
      "size": 12,
      "strides": Array [
        2,
      ],
    },
    "probability": Tensor {
      "dataId": Object {},
      "dtype": "float32",
      "id": 60785,
      "isDisposedInternal": false,
      "kept": false,
      "rankType": "1",
      "scopeId": 116495,
      "shape": Array [
        1,
      ],
      "size": 1,
      "strides": Array [],
    },
    "topLeft": Tensor {
      "dataId": Object {},
      "dtype": "float32",
      "id": 60792,
      "isDisposedInternal": false,
      "kept": false,
      "rankType": "1",
      "scopeId": 116526,
      "shape": Array [
        2,
      ],
      "size": 2,
      "strides": Array [],
    },
  },
]

标签: tensorflowdeep-learningtensorflow.js

解决方案


faces 不是张量。它是一个带有键值的 json 数组,其中值是张量。如果您想一次获取数组中的所有张量,Object.values(faces[0])可以使用

tensors = Object.values(faces[0]) // array of tensor
tensors.map(t => t.dataSync()) // download the value of the tensor to a js array

// alternatively they can all be converted to a big tensor before using only once dataSync()

推荐阅读