是否可以用require替换脚本标记src并在节点上运行相同的脚本?

问题描述 投票:0回答:2

我正在浏览器中运行以下程序:

INDEX.HTML(BODY)

<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中运行的脚本,如下所示:

INDEX.JS(IMPORT / ESM)

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

INDEX.JS(需要/与CONST一起使用)

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

INDEX.JS(要求/共用)

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)

node.js tensorflow require google-cloud-automl script-tag
2个回答
1
投票

对于其他想要在节点上运行张量流预测的人:


0
投票

我起初误解了您的问题。根据我现在所知道的,您需要不使用tfjs,而是使用本github问题中所述的tfjs-node

© www.soinside.com 2019 - 2024. All rights reserved.