Unable to Dynamically Import TensorFlow.js

U

user7147804

Guest
I am trying to dynamically import TensorFlow.js using the import function. However, I always receive a TypeError: t is undefined error. The following code is a simple HTML file which recreates the error.

!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/[email protected]/dist/tf.min.js")
.then(tf => { console.log(tf); });
</script>
</body>
</html>


Please note that I also desire to dynamically create the code that will use the TensorFlow.js library. Any help on how to dynamically import TensorFlow.js in the browser and run dynamically created code that uses its functions is much appreciated. Below is code that acts similarly to my end goal.

<!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/[email protected]/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>

Continue reading...
 
Top