В этом документе показано, как установить и использовать TensorFlow.js в браузере и в Node.js.
Настройка браузера
Существует два рекомендуемых способа использования TensorFlow.js в проектах, работающих в браузере:
Используйте тег <script> .
Установите из NPM и используйте инструмент сборки, например Parcel , webpack или Rollup .
Если вы новичок в веб-разработке или раньше не использовали инструменты сборки JavaScript, возможно, вам стоит сначала попробовать подход с использованием тегов <script>. Если же вы обычно собираете или обрабатываете свои веб-ресурсы, или планируете разрабатывать более крупные приложения, вам следует рассмотреть возможность использования инструментов сборки.
Используйте тег <script>
Чтобы использовать TensorFlow.js с помощью тега <script>, добавьте следующее в основной HTML-файл:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
В следующем примере показано, как определить и обучить модель в браузере:
<!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>
Чтобы запустить пример, выполните следующие действия:
- Сохраните пример документа в файл с именем
index.html. Дважды щелкните
index.html, чтобы открыть его в браузере по умолчанию.В качестве альтернативы, вы можете запустить
index.html, используяnpx http-serverв той же директории, что иindex.html. (Если вам будет предложено разрешить установкуhttp-server, введитеy.) Затем перейдите по адресуhttp://localhost:8080в вашем браузере.Откройте консоль браузера, чтобы увидеть вывод скрипта.
Обновите страницу, чтобы увидеть новый (и, скорее всего, другой) прогноз.
Установка из NPM
Для установки TensorFlow.js из NPM используйте либо CLI npm , либо yarn .
НПМ
npm install @tensorflow/tfjs
Пряжа
yarn add @tensorflow/tfjs
В следующем примере показано, как импортировать TensorFlow.js, определить модель и обучить её.
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
});
Настройка Node.js
Для использования TensorFlow.js в Node.js воспользуйтесь либо CLI npm , либо yarn , выбрав один из вариантов установки, указанных ниже.
Чтобы узнать больше об использовании TensorFlow.js в Node.js, см. руководство по Node.js. Дополнительную информацию по установке см. в репозитории TensorFlow.js для Node.js.
Вариант 1: Установите TensorFlow.js с нативными привязками C++.
Модуль tfjs-node обеспечивает нативное выполнение TensorFlow в приложениях JavaScript под управлением среды выполнения Node.js, ускоренное с помощью исполняемого файла TensorFlow на языке C.
Установите tfjs-node :
НПМ
npm install @tensorflow/tfjs-node
Пряжа
yarn add @tensorflow/tfjs-node
В следующем примере показано, как импортировать tfjs-node , определить модель и обучить её.
// 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}`)
}
});
Вариант 2: Установите TensorFlow.js для GPU.
(Только для Linux) Если ваша система оснащена графическим процессором NVIDIA® с поддержкой CUDA , вы можете использовать пакет для повышения производительности.
Установите tfjs-node-gpu :
НПМ
npm install @tensorflow/tfjs-node-gpu
Пряжа
yarn add @tensorflow/tfjs-node-gpu
В следующем примере показано, как импортировать tfjs-node-gpu , определить модель и обучить её.
// 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}`)
}
});
Вариант 3: Установите версию, содержащую только JavaScript.
Модуль tfjs — это тот же пакет, который вы используете в браузере. По производительности это самый медленный из вариантов Node.js.
Установите tfjs :
НПМ
npm install @tensorflow/tfjs
Пряжа
yarn add @tensorflow/tfjs
В следующем примере показано, как импортировать tfjs , определить модель и обучить её.
// 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}`)
}
});
Машинопись
Если вы используете TensorFlow.js в проекте TypeScript и у вас включена строгая проверка на null, вам может потребоваться установить skipLibCheck: true в файле tsconfig.json , чтобы избежать ошибок во время компиляции.