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

 所属分类:web前端开发

 浏览:44次-  评论: 0次-  更新时间:2023-09-13
描述:更多教程资料进入php教程获得。 机器学习 (ML) 彻底改变了各&#2001...
更多教程资料进入php教程获得。

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

机器学习 (ML) 彻底改变了各个行业,使计算机能够根据模式和数据进行学习和预测。传统上,机器学习模型是在服务器或高性能机器上构建和执行的。然而,随着 Web 技术的进步,现在可以使用 JavaScript 直接在浏览器中构建和部署 ML 模型。

在本文中,我们将探索 JavaScript 机器学习的激动人心的世界,并学习如何构建可以在浏览器中运行的 ML 模型。

了解机器学习

机器学习是人工智能 (AI) 的一个子集,专注于创建能够从数据中学习并做出预测或决策的模型。机器学习主要有两种类型:监督学习和无监督学习。

监督学习涉及在标记数据上训练模型,其中输入特征和相应的输出值是已知的。该模型从标记数据中学习模式,以对新的、未见过的数据进行预测。

另一方面,无监督学习处理未标记的数据。该模型无需任何预定义标签即可发现数据中隐藏的模式和结构。

JavaScript 机器学习库

要开始使用 JavaScript 机器学习,请按照以下步骤操作 -

第 1 步:安装 Node.js

Node.js 是一个 JavaScript 运行时环境,允许我们在 Web 浏览器之外运行 JavaScript 代码。它提供了使用 TensorFlow.js 所需的工具和库。

第 2 步:设置项目

安装 Node.js 后,打开您的首选代码编辑器并为您的 ML 项目创建一个新目录。使用命令行或终端导航到项目目录。

第 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 来定义、训练 ML 模型并进行预测。

让我们深入研究一些代码示例,以了解如何使用 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.
 标签:
积分说明:注册即送10金币,每日签到可获得更多金币,成为VIP会员可免金币下载! 充值积分充值会员更多说明»

讨论这个素材(0)回答他人问题或分享使用心得奖励金币

〒_〒 居然一个评论都没有……

表情  文明上网,理性发言!