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

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.