Thiết lập dự án TensorFlow.js

Tài liệu này hướng dẫn bạn cách cài đặt và sử dụng TensorFlow.js trong môi trường trình duyệt và trong Node.js.

Thiết lập trình duyệt

Có hai cách được khuyến nghị để sử dụng TensorFlow.js trong một dự án dựa trên trình duyệt:

Nếu bạn mới bắt đầu học phát triển web hoặc chưa từng sử dụng các công cụ biên dịch JavaScript trước đây, bạn có thể thử phương pháp sử dụng thẻ script trước. Nếu bạn thường xuyên đóng gói hoặc xử lý các tài nguyên web của mình, hoặc bạn dự định viết các ứng dụng lớn hơn, bạn nên cân nhắc sử dụng các công cụ biên dịch.

Sử dụng thẻ script

Để sử dụng TensorFlow.js với thẻ script, hãy thêm đoạn mã sau vào tệp HTML chính của bạn:

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>

Ví dụ sau đây minh họa cách định nghĩa và huấn luyện một mô hình trong trình duyệt:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>TensorFlow.js browser example</title>

    <!-- Load TensorFlow.js from a script tag -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
  </head>
  <body>
    <h1>TensorFlow.js example</h1>
    <h2>Open the console to see the results.</h2>
    <script>
    // Define a model for linear regression. The script tag makes `tf` available
    // as a global variable.
    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(() => {
      // Use the model to do inference on a data point the model hasn't seen before:
      model.predict(tf.tensor2d([5], [1, 1])).print();
      // Open the browser devtools to see the output
    });
    </script>
  </body>
</html>

Để chạy ví dụ, hãy làm theo các bước sau:

  1. Lưu tài liệu ví dụ vào một tệp có tên là index.html .
  2. Nhấp đúp vào index.html để mở nó trong trình duyệt mặc định của bạn.

    Ngoài ra, bạn cũng có thể phục vụ index.html bằng cách chạy lệnh npx http-server trong cùng thư mục với index.html . (Nếu được yêu cầu cấp quyền cài đặt http-server , hãy nhập y .) Sau đó, truy cập http://localhost:8080 trong trình duyệt của bạn.

  3. Mở bảng điều khiển trình duyệt để xem kết quả của tập lệnh.

  4. Hãy làm mới trang để xem dự đoán mới (và rất có thể là khác).

Cài đặt từ NPM

Để cài đặt TensorFlow.js từ NPM, hãy sử dụng công cụ dòng lệnh npm hoặc yarn .

NPM

npm install @tensorflow/tfjs

Sợi

yarn add @tensorflow/tfjs

Ví dụ sau đây minh họa cách nhập TensorFlow.js, định nghĩa một mô hình và huấn luyện mô hình đó.

import * as tf from '@tensorflow/tfjs';

// 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(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  model.predict(tf.tensor2d([5], [1, 1])).print();
  // Open the browser devtools to see the output
});

Thiết lập Node.js

Để sử dụng TensorFlow.js trong Node.js, hãy sử dụng CLI npm hoặc yarn để hoàn tất một trong các tùy chọn cài đặt bên dưới.

Để tìm hiểu thêm về cách sử dụng TensorFlow.js trong Node.js, hãy xem hướng dẫn Node.js. Để biết thêm thông tin cài đặt, hãy xem kho lưu trữ TensorFlow.js dành cho Node.js.

Phương án 1: Cài đặt TensorFlow.js với các liên kết C++ gốc.

Mô-đun tfjs-node cung cấp khả năng thực thi TensorFlow gốc trong các ứng dụng JavaScript trên môi trường Node.js, được tăng tốc bởi mã nhị phân C của TensorFlow.

Cài đặt tfjs-node :

NPM

npm install @tensorflow/tfjs-node

Sợi

yarn add @tensorflow/tfjs-node

Ví dụ sau đây minh họa cách nhập tfjs-node , định nghĩa một mô hình và huấn luyện mô hình đó.

// Use `tfjs-node`. Note that `tfjs` is imported indirectly by `tfjs-node`.
const tf = require('@tensorflow/tfjs-node');

// Define a simple model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 100, activation: 'relu', inputShape: [10]}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});

const xs = tf.randomNormal([100, 10]);
const ys = tf.randomNormal([100, 1]);

// Train the model.
model.fit(xs, ys, {
  epochs: 100,
  callbacks: {
    onEpochEnd: (epoch, log) => console.log(`Epoch ${epoch}: loss = ${log.loss}`)
  }
});

Phương án 2: Cài đặt TensorFlow.js cho GPU

(Chỉ dành cho Linux) Nếu hệ thống của bạn có GPU NVIDIA® hỗ trợ CUDA , bạn có thể sử dụng gói GPU để cải thiện hiệu suất.

Cài đặt tfjs-node-gpu :

NPM

npm install @tensorflow/tfjs-node-gpu

Sợi

yarn add @tensorflow/tfjs-node-gpu

Ví dụ sau đây minh họa cách nhập tfjs-node-gpu , định nghĩa một mô hình và huấn luyện mô hình đó.

// Use `tfjs-node-gpu`. Note that `tfjs` is imported indirectly by `tfjs-node-gpu`.
const tf = require('@tensorflow/tfjs-node-gpu');

// Define a simple model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 100, activation: 'relu', inputShape: [10]}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});

const xs = tf.randomNormal([100, 10]);
const ys = tf.randomNormal([100, 1]);

// Train the model.
model.fit(xs, ys, {
  epochs: 100,
  callbacks: {
    onEpochEnd: (epoch, log) => console.log(`Epoch ${epoch}: loss = ${log.loss}`)
  }
});

Phương án 3: Cài đặt phiên bản JavaScript thuần túy

Module tfjs là cùng một gói mà bạn sẽ sử dụng trong trình duyệt. Nó là tùy chọn chậm nhất trong số các tùy chọn của Node.js về hiệu năng.

Cài đặt tfjs :

NPM

npm install @tensorflow/tfjs

Sợi

yarn add @tensorflow/tfjs

Ví dụ sau đây minh họa cách nhập tfjs , định nghĩa một mô hình và huấn luyện mô hình đó.

// Use `tfjs`.
const tf = require('@tensorflow/tfjs');

// Define a simple model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 100, activation: 'relu', inputShape: [10]}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});

const xs = tf.randomNormal([100, 10]);
const ys = tf.randomNormal([100, 1]);

// Train the model.
model.fit(xs, ys, {
  epochs: 100,
  callbacks: {
    onEpochEnd: (epoch, log) => console.log(`Epoch ${epoch}: loss = ${log.loss}`)
  }
});

TypeScript

Nếu bạn đang sử dụng TensorFlow.js trong một dự án TypeScript và đã bật kiểm tra null nghiêm ngặt, bạn có thể cần đặt skipLibCheck: true trong tsconfig.json để tránh lỗi trong quá trình biên dịch.