gpt4 book ai didi

javascript - 无法动态导入 TensorFlow.js

转载 作者:行者123 更新时间:2023-11-29 22:46:44 25 4
gpt4 key购买 nike

我正在尝试使用 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>

最佳答案

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

const el = document.createElement('script')
el.src = "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js";
el.onload = (() => {
const script = document.createElement('script');
script.innerHTML = "console.log(tf)";
document.body.appendChild(script);
})();
document.body.appendChild(el);

备选

你也可以在前面附加脚本,但在加载 tf 之前不要执行

例子是

const script = document.createElement('script');
script.innerHTML = `
function someDependentCode() {
console.log(tf);
// put all dependent code string here
}
`;
document.body.appendChild(script); //code is added but not called

const el = document.createElement('script')
el.src = "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js";
el.onload = someDependentCode(); //dependent code can now execute
document.body.appendChild(el);

关于javascript - 无法动态导入 TensorFlow.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58255449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com