Tensorflow.js installation

Tensorflow.js installation

In JavaScript projects, there are two ways to install TensorFlow.js: one is to import through script tags, and the other is to install through npm.

For students who are not familiar with WEB development, we recommend using script tags to obtain them.

Use Script Tags

Add the following script tags to your main HTML file:

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>

See the code sample for script tag setup:

<html><head><!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script>
<!-- Place your code in the script tag below. You can also use an external .js file -->
<script>
      // Notice there is no 'import' statement. 'tf' is available on the index-page
      // because of the script tag above.

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

      // Prepare the model for training: Specify the loss and the optimizer.
      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).then(() => {
        // Use the model to do inference on a data point the model hasn't seen before:
        // Open the browser devtools to see the output
        model.predict(tf.tensor2d([5], [1, 1])).print();
      });
    </script></head><body></body></html>

via NPM (or yarn)

Add TensorFlow.js to your project using yarn or npm. Note: Because ES2017 syntax like import is used, this workflow assumes you use a packer/transformer to convert the code into something the browser can understand.

yarn add @tensorflow/tfjs  
或者
npm install @tensorflow/tfjs

Enter the following code in NPM:

import * as tf from '@tensorflow/tfjs';
//定义一个线性回归模型。
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// 为训练生成一些合成数据
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// 使用数据训练模型
model.fit(xs, ys, {epochs: 10}).then(() => { 
 // 在该模型从未看到过的数据点上使用模型进行推理 
 model.predict(tf.tensor2d([5], [1, 1])).print();  
//  打开浏览器开发工具查看输出});  

Guess you like

Origin blog.csdn.net/weixin_44692055/article/details/128704161