我正在浏览器中运行以下程序:
<script src="https://unpkg.com/@tensorflow/tfjs"></script>
<script src="https://unpkg.com/@tensorflow/tfjs-automl"></script>
<img
id="daisy"
crossorigin="anonymous"
src="https://storage.googleapis.com/tfjs-testing/tfjs-automl/img_classification/daisy.jpg"
/>
<script>
async function run() {
const model = await tf.automl.loadImageClassification("model.json");
const image = document.getElementById("daisy");
const predictions = await model.classify(image);
const pre = document.createElement("pre");
pre.textContent = JSON.stringify(predictions, null, 2);
document.body.append(pre);
}
run();
</script>
我正在尝试将脚本转换为可以在节点js中运行的脚本,如下所示:
import * as tf from "@tensorflow/tfjs";
import * as automl from "@tensorflow/tfjs-automl";
async function run() {
const model = await tf.automl.loadImageClassification("model.json");
const image = document.createElement("img");
image.src =
"https://storage.googleapis.com/tfjs-testing/tfjs-automl/img_classification/daisy.jpg";
const predictions = await model.classify(image);
console.log(predictions);
}
run();
然后我用node --experimental-modules index.js
运行脚本,但失败:
(node:24163) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'loadImageClassification' of undefined
我也尝试过require
:
const tf = require("@tensorflow/tfjs");
const automl = require("@tensorflow/tfjs-automl");
async function run() {
const model = await tf.automl.loadImageClassification("model.json");
const image = document.createElement("img");
image.src =
"https://storage.googleapis.com/tfjs-testing/tfjs-automl/img_classification/daisy.jpg";
const predictions = await model.classify(image);
console.log(predictions);
}
run();
我必须从"type": "module"
中删除package.json
并与node index index.js
一起运行。它给出了相同的错误。
我也尝试不捕获require
:
require("@tensorflow/tfjs");
require("@tensorflow/tfjs-automl");
async function run() {
const model = await tf.automl.loadImageClassification("model.json");
const image = document.createElement("img");
image.src =
"https://storage.googleapis.com/tfjs-testing/tfjs-automl/img_classification/daisy.jpg";
const predictions = await model.classify(image);
console.log(predictions);
}
run();
运行此命令时,出现错误:(node:24211) UnhandledPromiseRejectionWarning: ReferenceError: tf is not defined
。
这似乎很明显,但是有一种方法可以执行<script src=
的工作,但是在节点中,即引入外部脚本,以便我的脚本可以查看和使用外部脚本中的变量/方法?] >
我正在浏览器中运行以下命令:INDEX.HTML(BODY)
对于其他想要在节点上运行张量流预测的人:
我起初误解了您的问题。根据我现在所知道的,您需要不使用tfjs,而是使用本github问题中所述的tfjs-node