TensorflowJS无法读取NodeJS中undefined的属性“backend”

ve7v8dk2  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(163)

我已经看到了与此问题相关的问题,但我无法使其工作,即使与tfjs香草模块。
这是我的依赖:

"dependencies": {
    "@tensorflow/tfjs-backend-webgl": "^4.6.0",
    "@tensorflow/tfjs-core": "^4.6.0",
    "@tensorflow/tfjs-node": "^4.6.0",
    "canvas": "^2.11.2",
    "express": "^4.18.2",
    "fs": "^0.0.1-security",
    "jsdom": "^21.1.2",
    "node-cmd": "^5.0.0",
    "node-gyp": "^9.3.1",
    "path": "^0.12.7",
    "png-js": "^1.0.0",
    "xml-js": "^1.6.11"
}

首先,我加载de模块:

const tf = require('@tensorflow/tfjs-node');
require('@tensorflow/tfjs-backend-webgl');

然后加载模型:

const model = await tf.loadGraphModel(path);

然后对图像进行预处理:

const batched = tf.tidy(() => {
        const imageTensor = tf.browser.fromPixels(cnv);
        return (
          imageTensor
            //   .transpose([0, 1, 2])
            //.resizeBilinear([width, height])
            .resizeBilinear([width, height])
            .expandDims(0)
            .toInt()
        );
});

最后调用model.executeAsync:

return model.executeAsync(batched,["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"]).then(function (result){
    console.log("flag 0");
} //It never reaches the console log.

例外情况:

@tensorflow\tfjs-core\dist\tf-core.node.js:4519
    var srcBackend = info.backend;
                          ^

TypeError: Cannot read properties of undefined (reading 'backend')
    at Engine.moveData (\node_modules\@tensorflow\tfjs-core\dist\tf-core.node.js:4519:31)
    at DataStorage.get (\node_modules\@tensorflow\tfjs-core\dist\tf-core.node.js:230:28)
    at NodeJSKernelBackend.getInputTensorIds (\node_modules\@tensorflow\tfjs-node\dist\nodejs_kernel_backend.js:169:43)
    at NodeJSKernelBackend.executeSingleOutput (\node_modules\@tensorflow\tfjs-node\dist\nodejs_kernel_backend.js:216:73)
    at Object.kernelFunc (\node_modules\@tensorflow\tfjs-node\dist\kernels\Reshape.js:34:27)
    at kernelFunc (\node_modules\@tensorflow\tfjs-core\dist\tf-core.node.js:4704:32)
    at \node_modules\@tensorflow\tfjs-core\dist\tf-core.node.js:4764:27
    at Engine.scopedRun (\node_modules\@tensorflow\tfjs-core\dist\tf-core.node.js:4569:23)
    at Engine.runKernelFunc (\node_modules\@tensorflow\tfjs-core\dist\tf-core.node.js:4760:14)
    at Engine.runKernel (\node_modules\@tensorflow\tfjs-core\dist\tf-core.node.js:4633:21)

我在一个Python环境下运行Windows:Python 2.7(由tensorflowjs推荐)Node.js v18.15.0
我已经试过了我找到的每一个解决方案,我不知道我做错了什么。
我认为是一个bug:https://github.com/tensorflow/tfjs/issues/7706

zazmityj

zazmityj1#

在运行model.execAsync()之前尝试设置:await tf.setBackend('webgl') // Or 'wasm'。对我很有效。
在你的代码中写:

const predict = async (batched) => {
    await tf.setBackend('webgl'); // Or 'wasm'
    return model.executeAsync(batched, 
["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"]).then(function (result){
    console.log("flag 0");
} //It should reach the flag now
}

相关问题