Questo documento illustra come installare e utilizzare TensorFlow.js in un ambiente browser e in Node.js.
Impostazioni del browser
Esistono due metodi consigliati per utilizzare TensorFlow.js in un progetto basato su browser:
Utilizzare un tag script .
Installa tramite NPM e utilizza uno strumento di compilazione come Parcel , webpack o Rollup .
Se sei alle prime armi con lo sviluppo web o non hai mai utilizzato strumenti di build JavaScript, potresti provare prima l'approccio con i tag script. Se invece solitamente raggruppi o elabori le tue risorse web, o se prevedi di sviluppare applicazioni più complesse, dovresti valutare l'utilizzo di strumenti di build.
Utilizzare un tag script
Per includere TensorFlow.js tramite un tag script, aggiungi il seguente codice al tuo file HTML principale:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
L'esempio seguente mostra come definire e addestrare un modello nel browser:
<!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>
Per eseguire l'esempio, segui questi passaggi:
- Salva il documento di esempio in un file chiamato
index.html. Fai doppio clic su
index.htmlper aprirlo nel tuo browser predefinito.In alternativa, puoi servire
index.htmleseguendonpx http-servernella stessa directory diindex.html. (Se ti viene chiesto il permesso di installarehttp-server, digitay.) Dopodiché, vai ahttp://localhost:8080nel tuo browser.Apri la console del browser per visualizzare l'output dello script.
Aggiorna la pagina per visualizzare una nuova previsione (molto probabilmente diversa).
Installa tramite NPM
Per installare TensorFlow.js da NPM, usa la CLI di npm o yarn .
NPM
npm install @tensorflow/tfjs
Filato
yarn add @tensorflow/tfjs
L'esempio seguente mostra come importare TensorFlow.js, definire un modello e addestrarlo.
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
});
Configurazione di Node.js
Per utilizzare TensorFlow.js in Node.js, è possibile utilizzare la CLI di npm o yarn per completare una delle opzioni di installazione riportate di seguito.
Per ulteriori informazioni sull'utilizzo di TensorFlow.js in Node.js, consultare la guida di Node.js. Per ulteriori informazioni sull'installazione, consultare il repository di TensorFlow.js per Node.js.
Opzione 1: Installare TensorFlow.js con i binding nativi C++.
Il modulo tfjs-node fornisce l'esecuzione nativa di TensorFlow nelle applicazioni JavaScript all'interno dell'ambiente di runtime Node.js, accelerata dal binario C di TensorFlow.
Installa tfjs-node :
NPM
npm install @tensorflow/tfjs-node
Filato
yarn add @tensorflow/tfjs-node
L'esempio seguente mostra come importare tfjs-node , definire un modello e addestrare il modello.
// 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}`)
}
});
Opzione 2: Installare TensorFlow.js per GPU
(Solo Linux) Se il tuo sistema dispone di una GPU NVIDIA® con supporto CUDA , puoi utilizzare il pacchetto GPU per migliorare le prestazioni.
Installa tfjs-node-gpu :
NPM
npm install @tensorflow/tfjs-node-gpu
Filato
yarn add @tensorflow/tfjs-node-gpu
L'esempio seguente mostra come importare tfjs-node-gpu , definire un modello e addestrare il modello.
// 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}`)
}
});
Opzione 3: Installa la versione in puro JavaScript
Il modulo tfjs è lo stesso pacchetto che si usa nel browser. È l'opzione più lenta tra quelle disponibili per Node.js in termini di prestazioni.
Installa tfjs :
NPM
npm install @tensorflow/tfjs
Filato
yarn add @tensorflow/tfjs
L'esempio seguente mostra come importare tfjs , definire un modello e addestrare il modello.
// 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}`)
}
});
Dattiloscritto
Se stai utilizzando TensorFlow.js in un progetto TypeScript e hai abilitato il controllo rigoroso dei valori null, potresti dover impostare skipLibCheck: true nel tuo tsconfig.json per evitare errori durante la compilazione.