הגדר פרויקט TensorFlow.js

מסמך זה מראה לך כיצד להתקין ולהשתמש ב- TensorFlow.js בסביבת דפדפן וב-Node.js.

הגדרת דפדפן

ישנן שתי דרכים מומלצות להשתמש ב- TensorFlow.js בפרויקט מבוסס דפדפן:

אם אתה חדש בפיתוח אתרים, או שלא השתמשת בכלי בנייה של 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>

כדי להפעיל את הדוגמה, בצע את השלבים הבאים:

  1. שמור את המסמך לדוגמה בקובץ בשם index.html .
  2. לחץ פעמיים על index.html כדי לפתוח אותו בדפדפן ברירת המחדל שלך.

    לחלופין, אתה יכול לשרת index.html על ידי הפעלת npx http-server באותה ספרייה כמו index.html . (אם תתבקש להעניק רשות להתקין http-server , הזן y .) לאחר מכן עבור אל http://localhost:8080 בדפדפן שלך.

  3. פתח את מסוף הדפדפן כדי לראות את הפלט של הסקריפט.

  4. רענן את הדף כדי לראות תחזית חדשה (וכנראה שונה).

התקן מ-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 או בחוט כדי להשלים אחת מאפשרויות ההתקנה שלהלן.

למידע נוסף על השימוש ב-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® GPU עם תמיכה ב-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}`)
  }
});

TypeScript

אם אתה משתמש ב-TensorFlow.js בפרויקט TypeScript, והפעלת בדיקת null קפדנית, ייתכן שיהיה עליך להגדיר skipLibCheck: true ב- tsconfig.json שלך כדי למנוע שגיאות במהלך ההידור.