قم بإعداد مشروع 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 أو الغزل .

الآلية الوقائية الوطنية

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 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 لوحدة معالجة الرسومات

(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، وقمت بتمكين التحقق من القيم الخالية، فقد تحتاج إلى تعيين skipLibCheck: true في tsconfig.json الخاص بك لتجنب الأخطاء أثناء التحويل البرمجي.