无法动态导入TensorFlow.js

时间:2019-10-06 08:17:06

标签: javascript tensorflow

我正在尝试使用import函数动态导入TensorFlow.js。但是,我总是收到一个TypeError: t is undefined错误。以下代码是一个简单的HTML文件,可重新创建错误。

!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
import("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js")
  .then(tf => { console.log(tf); });
  </script>
</body>
</html>

请注意,我还希望动态创建将使用TensorFlow.js库的代码。非常感谢您提供有关如何在浏览器中动态导入TensorFlow.js以及运行使用其功能的动态创建代码的帮助。下面是与我的最终目标相似的代码。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
let code = `import("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js").then(tf => {

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

// Train the model using the data.
model.fit(xs, ys, {epochs: 10}).then(() => {
model.predict(tf.tensor2d([5], [1, 1])).print();
// Open the browser devtools to see the output
});

});
`;

let script = document.createElement("script");
script.type = "text/javascript";
script.appendChild(document.createTextNode(code));
document.body.appendChild(script);
  </script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您可以很好地动态添加脚本元素吗?

D * dot(P-A, D)

替代

您还可以更早地添加脚本,但是要等到tf加载后才能执行

示例是

function isPointbetweenTwoOthers (pA, pB, pToCheck) {

    let vAtoB = pB.clone().sub(pA);
    let vAtoC = pToCheck.clone().sub(pA);
    let vBtoC = pToCheck.clone().sub(pB);

    // fast exit, C can't be between A and B
    if (nvAtoB.dot(nvAtoC) < 0.0 || nvAtoB.dot(nvBtoC) > 0.0)
       return false;

    // nearest point X to C on the line A, B
    let X = pA.clone().add( vAtoC.clone().projectOnVector( vAtoB ) );

    // distance between X and C
    let distXtoC = X.distanceTo( C );

    let threshold = 1.0; // ???
    return distXtoC < threshold;
}