您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2025/12/9 19:51:08发布17次查看
机器学习 (ml) 彻底改变了各个行业,使计算机能够根据模式和数据进行学习和预测。传统上,机器学习模型是在服务器或高性能机器上构建和执行的。然而,随着 web 技术的进步,现在可以使用 javascript 直接在浏览器中构建和部署 ml 模型。
在本文中,我们将探索 javascript 机器学习的激动人心的世界,并学习如何构建可以在浏览器中运行的 ml 模型。
了解机器学习机器学习是人工智能 (ai) 的一个子集,专注于创建能够从数据中学习并做出预测或决策的模型。机器学习主要有两种类型:监督学习和无监督学习。
监督学习涉及在标记数据上训练模型,其中输入特征和相应的输出值是已知的。该模型从标记数据中学习模式,以对新的、未见过的数据进行预测。
另一方面,无监督学习处理未标记的数据。该模型无需任何预定义标签即可发现数据中隐藏的模式和结构。
javascript 机器学习库要开始使用 javascript 机器学习,请按照以下步骤操作 -
第 1 步:安装 node.jsnode.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 libraryimport * as tf from '@tensorflow/tfjs';// define input features and output valuesconst inputfeatures = tf.tensor2d([[1], [2], [3], [4], [5]], [5, 1]);const outputvalues = tf.tensor2d([[2], [4], [6], [8], [10]], [5, 1]);// define the model architectureconst model = tf.sequential();model.add(tf.layers.dense({ units: 1, inputshape: [1] }));// compile the modelmodel.compile({ optimizer: 'sgd', loss: 'meansquarederror' });// train the modelmodel.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 libraryimport * as tf from '@tensorflow/tfjs';import '@tensorflow/tfjs-node'; // required for node.js environment// define training dataconst 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 dataconst texts = trainingdata.map(item => item.text);const labels = trainingdata.map(item => (item.sentiment === 'positive' ? 1 : 0));// tokenize and preprocess the textsconst 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 sequencesconst 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 tensorsconst paddedsequencestensor = tf.tensor2d(paddedsequences);const labelstensor = tf.tensor1d(labels);// define the model architectureconst 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 modelmodel.compile({ optimizer: 'adam', loss: 'binarycrossentropy', metrics: ['accuracy'] });// train the modelmodel.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 / 10eta=0.0 ========================================================================> 14ms 4675us/step - acc=0.00 loss=0.708 epoch 2 / 10eta=0.0 ========================================================================> 4ms 1428us/step - acc=0.667 loss=0.703 epoch 3 / 10eta=0.0 ========================================================================> 5ms 1733us/step - acc=0.667 loss=0.697 epoch 4 / 10eta=0.0 ========================================================================> 4ms 1419us/step - acc=0.667 loss=0.692 epoch 5 / 10eta=0.0 ========================================================================> 6ms 1944us/step - acc=0.667 loss=0.686 epoch 6 / 10eta=0.0 ========================================================================> 5ms 1558us/step - acc=0.667 loss=0.681 epoch 7 / 10eta=0.0 ========================================================================> 5ms 1513us/step - acc=0.667 loss=0.675 epoch 8 / 10eta=0.0 ========================================================================> 3ms 1057us/step - acc=1.00 loss=0.670 epoch 9 / 10eta=0.0 ========================================================================> 5ms 1745us/step - acc=1.00 loss=0.665 epoch 10 / 10eta=0.0 ========================================================================> 4ms 1439us/step - acc=1.00 loss=0.659 the sentiment of this product exceeded my expectations! is positive.
以上就是javascript 机器学习:在浏览器中构建 ml 模型的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product