Home >Web Front-end >JS Tutorial >JavaScript Machine Learning: Build ML Models in the Browser

JavaScript Machine Learning: Build ML Models in the Browser

王林
王林forward
2023-09-10 09:45:021358browse

JavaScript 机器学习:在浏览器中构建 ML 模型

Machine learning (ML) has revolutionized industries by enabling computers to learn and predict based on patterns and data. Traditionally, machine learning models are built and executed on servers or high-performance machines. However, as web technology advances, it is now possible to build and deploy ML models directly in the browser using JavaScript.

In this article, we’ll explore the exciting world of JavaScript machine learning and learn how to build ML models that can run in the browser.

Understanding Machine Learning

Machine learning is a subset of artificial intelligence (AI) that focuses on creating models that can learn from data and make predictions or decisions. There are two main types of machine learning: supervised learning and unsupervised learning.

Supervised learning involves training a model on labeled data, where the input features and corresponding output values ​​are known. The model learns patterns from labeled data to make predictions on new, unseen data.

Unsupervised learning, on the other hand, deals with unlabeled data. The model discovers hidden patterns and structures in data without any predefined labels.

JavaScript Machine Learning Library

To get started with JavaScript machine learning, follow these steps -

Step 1: Install Node.js

Node.js is a JavaScript runtime environment that allows us to run JavaScript code outside of a web browser. It provides the tools and libraries needed to use TensorFlow.js.

Step 2: Set up the project

After installing Node.js, open your preferred code editor and create a new directory for your ML project. Navigate to the project directory using the command line or terminal.

Step 3: Initialize the Node.js project

In the command line or terminal, run the following command to initialize the new Node.js project -

npm init -y

This command creates a new package.json file for managing project dependencies and configuration.

Step 4: Install TensorFlow.js

To install TensorFlow.js, run the following command in the command line or terminal -

npm install @tensorflow/tfjs

Step 5: Start building the machine learning model

Now that your project is set up and TensorFlow.js is installed, you can start building machine learning models in the browser. You can create a new JavaScript file, import TensorFlow.js, and use its API to define, train an ML model, and make predictions.

Let’s dive into some code examples to learn how to use TensorFlow.js and build machine learning models in JavaScript.

Example 1: Linear Regression

Linear regression is a supervised learning algorithm used to predict continuous output values ​​based on input features.

Let’s see how to implement linear regression using 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();
});

illustrate

In this example, we first import the TensorFlow.js library. Then, we define the input features and output values ​​as tensors. Next, we create a sequential model and add a dense layer with one unit. We compile the model using the "sgd" optimizer and the "meanSquaredError" loss function. Finally, we train the model for 100 epochs and make predictions on the input features. The predicted output values ​​are printed to the console.

Output

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

Example 2: Sentiment Analysis

Sentiment analysis is a popular application of machine learning that involves analyzing text data to determine the emotion or emotional tone expressed in the text. We can use TensorFlow.js to build a sentiment analysis model that predicts whether a given text has positive or negative sentiment.

Consider the code shown below.

// 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}.`);
});

Output

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.

The above is the detailed content of JavaScript Machine Learning: Build ML Models in the Browser. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete