JavaScript 機器學習:在瀏覽器中構建機器學習模型


機器學習 (ML) 徹底改變了各個行業,使計算機能夠根據模式和資料進行學習和預測。傳統上,機器學習模型是在伺服器或高效能機器上構建和執行的。然而,隨著 Web 技術的進步,現在可以使用 JavaScript 直接在瀏覽器中構建和部署機器學習模型。

在本文中,我們將探索 JavaScript 機器學習的精彩世界,並學習如何構建可以在瀏覽器中執行的機器學習模型。

理解機器學習

機器學習是人工智慧 (AI) 的一個子集,專注於建立能夠從資料中學習並進行預測或決策的模型。主要有兩種型別的機器學習:監督學習和無監督學習。

監督學習包括使用標記資料訓練模型,其中輸入特徵和相應的輸出值是已知的。模型從標記資料中學習模式,以便對新的、未見過的資料進行預測。

另一方面,無監督學習處理未標記的資料。模型在沒有任何預定義標籤的情況下發現資料中的隱藏模式和結構。

JavaScript 機器學習庫

要開始使用 JavaScript 機器學習,請按照以下步驟操作:

步驟 1:安裝 Node.js

Node.js 是一個 JavaScript 執行時環境,允許我們在 Web 瀏覽器之外執行 JavaScript 程式碼。它提供使用 TensorFlow.js 所需的工具和庫。

步驟 2:設定專案

安裝 Node.js 後,開啟你首選的程式碼編輯器併為你的機器學習專案建立一個新目錄。使用命令列或終端導航到專案目錄。

步驟 3:初始化 Node.js 專案

在命令列或終端中,執行以下命令以初始化一個新的 Node.js 專案:

npm init -y

此命令建立一個新的 package.json 檔案,用於管理專案依賴項和配置。

步驟 4:安裝 TensorFlow.js

要安裝 TensorFlow.js,請在命令列或終端中執行以下命令:

npm install @tensorflow/tfjs

步驟 5:開始構建機器學習模型

現在你的專案已設定好並且 TensorFlow.js 已安裝,你就可以開始在瀏覽器中構建機器學習模型了。你可以建立一個新的 JavaScript 檔案,匯入 TensorFlow.js,並使用其 API 來定義、訓練和使用機器學習模型進行預測。

讓我們深入研究一些程式碼示例,以瞭解如何使用 TensorFlow.js 和在 JavaScript 中構建機器學習模型。

示例 1:線性迴歸

線性迴歸是一種監督學習演算法,用於根據輸入特徵預測連續輸出值。

讓我們看看如何使用 TensorFlow.js 實現線性迴歸。

// Import TensorFlow.js library
import * as tf from '@tensorflow/tfjs';

// Define input features and output values
const inputFeatures = tf.tensor2d([[1], [2], [3], [4], [5]], [5, 1]);
const outputValues = tf.tensor2d([[2], [4], [6], [8], [10]], [5, 1]);

// Define the model architecture
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [1] }));

// Compile the model
model.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });

// Train the model
model.fit(inputFeatures, outputValues, { epochs: 100 }).then(() => {
   // Make predictions
   const predictions = model.predict(inputFeatures);

   // Print predictions
   predictions.print();
});

解釋

在這個示例中,我們首先匯入 TensorFlow.js 庫。然後,我們將輸入特徵和輸出值定義為張量。接下來,我們建立一個順序模型並新增一個具有一個單元的密集層。我們使用 'sgd' 最佳化器和 'meanSquaredError' 損失函式編譯模型。最後,我們訓練模型 100 個 epoch 並對輸入特徵進行預測。預測的輸出值列印到控制檯。

輸出

Tensor
   [2.2019906],
   [4.124609 ],
   [6.0472274],
   [7.9698458],
   [9.8924646]]

示例 2:情感分析

情感分析是機器學習的一個流行應用,它涉及分析文字資料以確定文字中表達的情感或情緒基調。我們可以使用 TensorFlow.js 來構建一個情感分析模型,該模型可以預測給定文字是正面情緒還是負面情緒。

請考慮以下程式碼。

// Import TensorFlow.js library
import * as tf from '@tensorflow/tfjs';
import '@tensorflow/tfjs-node'; // Required for Node.js environment

// Define training data
const trainingData = [
   { text: 'I love this product!', sentiment: 'positive' },
   { text: 'This is a terrible experience.', sentiment: 'negative' },
   { text: 'The movie was amazing!', sentiment: 'positive' },
   // Add more training data...
];

// Prepare training data
const texts = trainingData.map(item => item.text);
const labels = trainingData.map(item => (item.sentiment === 'positive' ? 1 : 0));

// Tokenize and preprocess the texts
const tokenizedTexts = texts.map(text => text.toLowerCase().split(' '));
const wordIndex = new Map();
let currentIndex = 1;
const sequences = tokenizedTexts.map(tokens => {
   return tokens.map(token => {
      if (!wordIndex.has(token)) {
         wordIndex.set(token, currentIndex);
         currentIndex++;
      }
      return wordIndex.get(token);
   });
});

// Pad sequences
const maxLength = sequences.reduce((max, seq) => Math.max(max, seq.length), 0);
const paddedSequences = sequences.map(seq => {
   if (seq.length < maxLength) {
      return seq.concat(new Array(maxLength - seq.length).fill(0));
   }
   return seq;
});

// Convert to tensors
const paddedSequencesTensor = tf.tensor2d(paddedSequences);
const labelsTensor = tf.tensor1d(labels);

// Define the model architecture
const model = tf.sequential();
model.add(tf.layers.embedding({ inputDim: currentIndex, outputDim: 16, inputLength: maxLength }));
model.add(tf.layers.flatten());
model.add(tf.layers.dense({ units: 1, activation: 'sigmoid' }));

// Compile the model
model.compile({ optimizer: 'adam', loss: 'binaryCrossentropy', metrics: ['accuracy'] });

// Train the model
model.fit(paddedSequencesTensor, labelsTensor, { epochs: 10 }).then(() => {
   // Make predictions
   const testText = 'This product exceeded my expectations!';
   const testTokens = testText.toLowerCase().split(' ');
   const testSequence = testTokens.map(token => {
      if (wordIndex.has(token)) {
         return wordIndex.get(token);
      }
      return 0;
   });
   const paddedTestSequence = testSequence.length < maxLength ? testSequence.concat(new Array(maxLength - testSequence.length).fill(0)) : testSequence;
   const testSequenceTensor = tf.tensor2d([paddedTestSequence]);
   const prediction = model.predict(testSequenceTensor);
   const sentiment = prediction.dataSync()[0] > 0.5 ?  'positive' : 'negative';

   // Print the sentiment prediction
   console.log(`The sentiment of "${testText}" is ${sentiment}.`);
});

輸出

Epoch 1 / 10
eta=0.0 ========================================================================> 
14ms 4675us/step - acc=0.00 loss=0.708 
Epoch 2 / 10
eta=0.0 ========================================================================> 
4ms 1428us/step - acc=0.667 loss=0.703 
Epoch 3 / 10
eta=0.0 ========================================================================> 
5ms 1733us/step - acc=0.667 loss=0.697 
Epoch 4 / 10
eta=0.0 ========================================================================> 
4ms 1419us/step - acc=0.667 loss=0.692 
Epoch 5 / 10
eta=0.0 ========================================================================> 
6ms 1944us/step - acc=0.667 loss=0.686 
Epoch 6 / 10
eta=0.0 ========================================================================> 
5ms 1558us/step - acc=0.667 loss=0.681 
Epoch 7 / 10
eta=0.0 ========================================================================> 
5ms 1513us/step - acc=0.667 loss=0.675 
Epoch 8 / 10
eta=0.0 ========================================================================> 
3ms 1057us/step - acc=1.00 loss=0.670 
Epoch 9 / 10
eta=0.0 ========================================================================> 
5ms 1745us/step - acc=1.00 loss=0.665 
Epoch 10 / 10
eta=0.0 ========================================================================> 
4ms 1439us/step - acc=1.00 loss=0.659 
The sentiment of "This product exceeded my expectations!" is positive.

更新於:2023-07-25

瀏覽量 232

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告