מסמך זה מראה לכם כיצד להתקין ולהשתמש ב-TensorFlow.js בסביבת דפדפן וב-Node.js.
הגדרת דפדפן
ישנן שתי דרכים מומלצות לשימוש ב-TensorFlow.js בפרויקט מבוסס דפדפן:
השתמש בתגית סקריפט .
התקן מ- NPM והשתמש בכלי בנייה כמו Parcel , webpack או Rollup .
אם אתם חדשים בפיתוח אתרים, או שלא השתמשתם בעבר בכלי בנייה של JavaScript, ייתכן שתרצו לנסות תחילה את גישת תג הסקריפט. אם אתם בדרך כלל מעבדים או מאגדים את נכסי האינטרנט שלכם, או שאתם מתכננים לכתוב יישומים גדולים יותר, כדאי לכם לשקול להשתמש בכלי בנייה.
השתמש בתגית סקריפט
כדי לקבל את TensorFlow.js באמצעות תג סקריפט, הוסף את הפרטים הבאים לקובץ ה-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, השתמש ב- npm CLI או ב-yarn .
NPM
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, השתמש ב- npm CLI או ב-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
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
(לינוקס בלבד) אם למערכת שלך יש כרטיס מסך של NVIDIA® עם תמיכה ב-CUDA , תוכל להשתמש בחבילת ה-GPU לשיפור הביצועים.
התקן tfjs-node-gpu :
NPM
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
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 strict, ייתכן שתצטרכו להגדיר skipLibCheck: true בקובץ tsconfig.json כדי למנוע שגיאות במהלך הקומפילציה.