model.predict.datasync()需要时间来给出导致相机延迟的结果.如何立即获得结果/预测?



我在react native中使用Tensorflow js,我正在为我的模型获得正确的预测,但需要很多时间才能给出结果。例如,我使用的是我在谷歌的可教机器中创建的自定义模型。但是.datasync()大约需要花费时间。1秒整给出结果。这会导致相机的物理滞后,我想立即得到结果。下面是我的代码:-

<TensorCamera
style={styles.camera}
flashMode={Camera.Constants.FlashMode.off}
type={Camera.Constants.Type.back}
resizeWidth={224}
resizeHeight={224}
resizeDepth={3}
onReady={handleCameraStream}
autorender={true}
/>
//
const handleCameraStream = (imageAsTensors) => {
try {
} catch (e) {
// console.log("Tensor 1 not found!");
}
const loop = async () => {
// && detected == true
if (model !== null) {
if (frameCount % makePredictionsEveryNFrames === 0) {
const imageTensor = imageAsTensors.next().value;
await getPrediction(imageTensor);
// .catch(e => console.log(e));
}
}
frameCount += 1;
frameCount = frameCount % makePredictionsEveryNFrames;
requestAnimationFrameId = requestAnimationFrame(loop);
};
loop();
//loop infinitely to constantly make predictions
};
//
const getPrediction = async (tensor) => {
// if (!videoLink) {
if (!tensor) {
console.log("Tensor not found!");
return;
}
//
const imageData2 = tensor.resizeBilinear([224, 224]);
// tf.image.resizeBilinear(tensor, [224, 224]);
const normalized = imageData2.cast("float32").div(127.5).sub(1);
const final = tf.expandDims(normalized, 0);
//
console.time();
const prediction = model.predict(final).dataSync();

console.timeEnd();
console.log("Predictions:", prediction);
}

我听说使用。data()而不是。datasync(),但我不知道如何在我当前的代码中实现。data()。请帮助。

predict是需要时间的-这真的取决于你的模型
也许它可以在不同的后端运行得更快(不知道你使用的是哪个后端,浏览器默认是webgl),但实际上它是没有重新构建模型项目的。

datasync只是下载结果从张量在哪里(例如在gpu vram)到你的变量在js。

是的,你可以使用data来代替,这是一个异步调用,但区别最多是几毫秒-它根本不会加速模型执行。

顺便说一句,你没有在任何地方释放张量——你的应用程序有一些严重的内存泄漏。

最新更新