前端AI机器学习在浏览器中训练模型

目录
  • 识别鸢尾花
    • 测试集: testing.json
    • 训练集: training.json
  • 完整代码
    • index.html
    • index.js
    • styles.css
    • package.json

识别鸢尾花

本文将在浏览器中定义、训练和运行模型。 为了实现这一功能,我将构建一个识别鸢尾花的案例。

接下来,我们将创建一个神经网络。同时,根据开源数据集我们将鸢尾花分为三类:Setosa、Virginica 和 Versicolor。

每个机器学习项目的核心都是数据集。 我们需要采取的第一步是将这个数据集拆分为训练集和测试集

这样做的原因是我们将使用我们的训练集来训练我们的算法和我们的测试集来检查我们的预测的准确性,以验证我们的模型是否可以使用或需要调整。

为了方便起见,我已经将训练集和测试集拆分为两个 JSON 文件:

测试集: testing.json

[{"sepal_length":6,"sepal_width":2.9,"petal_length":4.5,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":5.2,"sepal_width":3.4,"petal_length":1.4,"petal_width":0.2,"species":"setosa"},
{"sepal_length":6.5,"sepal_width":3,"petal_length":5.8,"petal_width":2.2,"species":"virginica"},
{"sepal_length":5.9,"sepal_width":3.2,"petal_length":4.8,"petal_width":1.8,"species":"versicolor"},
{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.9,"petal_width":0.4,"species":"setosa"},
{"sepal_length":5.4,"sepal_width":3,"petal_length":4.5,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":7,"sepal_width":3.2,"petal_length":4.7,"petal_width":1.4,"species":"versicolor"},
{"sepal_length":5.7,"sepal_width":2.8,"petal_length":4.5,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":5.1,"sepal_width":2.5,"petal_length":3,"petal_width":1.1,"species":"versicolor"},
{"sepal_length":4.9,"sepal_width":2.4,"petal_length":3.3,"petal_width":1,"species":"versicolor"},
{"sepal_length":5.1,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.4,"species":"setosa"},
{"sepal_length":5.7,"sepal_width":2.8,"petal_length":4.1,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":5.6,"sepal_width":3,"petal_length":4.5,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":6.1,"sepal_width":3,"petal_length":4.6,"petal_width":1.4,"species":"versicolor"}]

训练集: training.json

[{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.9,"sepal_width":3,"petal_length":1.4,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.7,"sepal_width":3.2,"petal_length":1.3,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.6,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5,"sepal_width":3.6,"petal_length":1.4,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.6,"sepal_width":3.4,"petal_length":1.4,"petal_width":0.3,"species":"setosa"},
{"sepal_length":5,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.4,"sepal_width":2.9,"petal_length":1.4,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"species":"setosa"},
{"sepal_length":5.4,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.8,"sepal_width":3.4,"petal_length":1.6,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.8,"sepal_width":3,"petal_length":1.4,"petal_width":0.1,"species":"setosa"},
{"sepal_length":4.3,"sepal_width":3,"petal_length":1.1,"petal_width":0.1,"species":"setosa"},
{"sepal_length":5.8,"sepal_width":4,"petal_length":1.2,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5.7,"sepal_width":4.4,"petal_length":1.5,"petal_width":0.4,"species":"setosa"},
{"sepal_length":5.4,"sepal_width":3.9,"petal_length":1.3,"petal_width":0.4,"species":"setosa"},
{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.3,"species":"setosa"},
{"sepal_length":5.7,"sepal_width":3.8,"petal_length":1.7,"petal_width":0.3,"species":"setosa"},
{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.5,"petal_width":0.3,"species":"setosa"},
{"sepal_length":5.4,"sepal_width":3.4,"petal_length":1.7,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.6,"sepal_width":3.6,"petal_length":1,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5.1,"sepal_width":3.3,"petal_length":1.7,"petal_width":0.5,"species":"setosa"},
{"sepal_length":4.8,"sepal_width":3.4,"petal_length":1.9,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5,"sepal_width":3,"petal_length":1.6,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5,"sepal_width":3.4,"petal_length":1.6,"petal_width":0.4,"species":"setosa"},
{"sepal_length":5.2,"sepal_width":3.5,"petal_length":1.5,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.7,"sepal_width":3.2,"petal_length":1.6,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.8,"sepal_width":3.1,"petal_length":1.6,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5.4,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.4,"species":"setosa"},
{"sepal_length":5.2,"sepal_width":4.1,"petal_length":1.5,"petal_width":0.1,"species":"setosa"},
{"sepal_length":5.5,"sepal_width":4.2,"petal_length":1.4,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"species":"setosa"},
{"sepal_length":5,"sepal_width":3.2,"petal_length":1.2,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5.5,"sepal_width":3.5,"petal_length":1.3,"petal_width":0.2,"species":"setosa"},
{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"species":"setosa"},
{"sepal_length":4.4,"sepal_width":3,"petal_length":1.3,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5.1,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5,"sepal_width":3.5,"petal_length":1.3,"petal_width":0.3,"species":"setosa"},
{"sepal_length":4.5,"sepal_width":2.3,"petal_length":1.3,"petal_width":0.3,"species":"setosa"},
{"sepal_length":4.4,"sepal_width":3.2,"petal_length":1.3,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5,"sepal_width":3.5,"petal_length":1.6,"petal_width":0.6,"species":"setosa"},
{"sepal_length":4.8,"sepal_width":3,"petal_length":1.4,"petal_width":0.3,"species":"setosa"},
{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.6,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5.3,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.2,"species":"setosa"},
{"sepal_length":5,"sepal_width":3.3,"petal_length":1.4,"petal_width":0.2,"species":"setosa"},
{"sepal_length":6.4,"sepal_width":3.2,"petal_length":4.5,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":5.5,"sepal_width":2.3,"petal_length":4,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":6.5,"sepal_width":2.8,"petal_length":4.6,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":6.3,"sepal_width":3.3,"petal_length":4.7,"petal_width":1.6,"species":"versicolor"},
{"sepal_length":6.6,"sepal_width":2.9,"petal_length":4.6,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":5.2,"sepal_width":2.7,"petal_length":3.9,"petal_width":1.4,"species":"versicolor"},
{"sepal_length":5,"sepal_width":2,"petal_length":3.5,"petal_width":1,"species":"versicolor"},
{"sepal_length":5.9,"sepal_width":3,"petal_length":4.2,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":6,"sepal_width":2.2,"petal_length":4,"petal_width":1,"species":"versicolor"},
{"sepal_length":6.1,"sepal_width":2.9,"petal_length":4.7,"petal_width":1.4,"species":"versicolor"},
{"sepal_length":5.6,"sepal_width":2.9,"petal_length":3.6,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":6.7,"sepal_width":3.1,"petal_length":4.4,"petal_width":1.4,"species":"versicolor"},
{"sepal_length":5.8,"sepal_width":2.7,"petal_length":4.1,"petal_width":1,"species":"versicolor"},
{"sepal_length":6.2,"sepal_width":2.2,"petal_length":4.5,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":5.6,"sepal_width":2.5,"petal_length":3.9,"petal_width":1.1,"species":"versicolor"},
{"sepal_length":6.1,"sepal_width":2.8,"petal_length":4,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":6.3,"sepal_width":2.5,"petal_length":4.9,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":6.1,"sepal_width":2.8,"petal_length":4.7,"petal_width":1.2,"species":"versicolor"},
{"sepal_length":6.4,"sepal_width":2.9,"petal_length":4.3,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":6.6,"sepal_width":3,"petal_length":4.4,"petal_width":1.4,"species":"versicolor"},
{"sepal_length":6.8,"sepal_width":2.8,"petal_length":4.8,"petal_width":1.4,"species":"versicolor"},
{"sepal_length":6.7,"sepal_width":3,"petal_length":5,"petal_width":1.7,"species":"versicolor"},
{"sepal_length":5.7,"sepal_width":2.6,"petal_length":3.5,"petal_width":1,"species":"versicolor"},
{"sepal_length":5.5,"sepal_width":2.4,"petal_length":3.8,"petal_width":1.1,"species":"versicolor"},
{"sepal_length":5.5,"sepal_width":2.4,"petal_length":3.7,"petal_width":1,"species":"versicolor"},
{"sepal_length":5.8,"sepal_width":2.7,"petal_length":3.9,"petal_width":1.2,"species":"versicolor"},
{"sepal_length":6,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.6,"species":"versicolor"},
{"sepal_length":6,"sepal_width":3.4,"petal_length":4.5,"petal_width":1.6,"species":"versicolor"},
{"sepal_length":6.7,"sepal_width":3.1,"petal_length":4.7,"petal_width":1.5,"species":"versicolor"},
{"sepal_length":6.3,"sepal_width":2.3,"petal_length":4.4,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":5.6,"sepal_width":3,"petal_length":4.1,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":5.5,"sepal_width":2.5,"petal_length":4,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":5.5,"sepal_width":2.6,"petal_length":4.4,"petal_width":1.2,"species":"versicolor"},
{"sepal_length":5.8,"sepal_width":2.6,"petal_length":4,"petal_width":1.2,"species":"versicolor"},
{"sepal_length":5,"sepal_width":2.3,"petal_length":3.3,"petal_width":1,"species":"versicolor"},
{"sepal_length":5.6,"sepal_width":2.7,"petal_length":4.2,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":5.7,"sepal_width":3,"petal_length":4.2,"petal_width":1.2,"species":"versicolor"},
{"sepal_length":6.2,"sepal_width":2.9,"petal_length":4.3,"petal_width":1.3,"species":"versicolor"},
{"sepal_length":6.3,"sepal_width":3.3,"petal_length":6,"petal_width":2.5,"species":"virginica"},
{"sepal_length":5.8,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.9,"species":"virginica"},
{"sepal_length":7.1,"sepal_width":3,"petal_length":5.9,"petal_width":2.1,"species":"virginica"},
{"sepal_length":6.3,"sepal_width":2.9,"petal_length":5.6,"petal_width":1.8,"species":"virginica"},
{"sepal_length":7.6,"sepal_width":3,"petal_length":6.6,"petal_width":2.1,"species":"virginica"},
{"sepal_length":4.9,"sepal_width":2.5,"petal_length":4.5,"petal_width":1.7,"species":"virginica"},
{"sepal_length":7.3,"sepal_width":2.9,"petal_length":6.3,"petal_width":1.8,"species":"virginica"},
{"sepal_length":6.7,"sepal_width":2.5,"petal_length":5.8,"petal_width":1.8,"species":"virginica"},
{"sepal_length":7.2,"sepal_width":3.6,"petal_length":6.1,"petal_width":2.5,"species":"virginica"},
{"sepal_length":6.5,"sepal_width":3.2,"petal_length":5.1,"petal_width":2,"species":"virginica"},
{"sepal_length":6.4,"sepal_width":2.7,"petal_length":5.3,"petal_width":1.9,"species":"virginica"},
{"sepal_length":6.8,"sepal_width":3,"petal_length":5.5,"petal_width":2.1,"species":"virginica"},
{"sepal_length":5.7,"sepal_width":2.5,"petal_length":5,"petal_width":2,"species":"virginica"},
{"sepal_length":5.8,"sepal_width":2.8,"petal_length":5.1,"petal_width":2.4,"species":"virginica"},
{"sepal_length":6.4,"sepal_width":3.2,"petal_length":5.3,"petal_width":2.3,"species":"virginica"},
{"sepal_length":6.5,"sepal_width":3,"petal_length":5.5,"petal_width":1.8,"species":"virginica"},
{"sepal_length":7.7,"sepal_width":3.8,"petal_length":6.7,"petal_width":2.2,"species":"virginica"},
{"sepal_length":7.7,"sepal_width":2.6,"petal_length":6.9,"petal_width":2.3,"species":"virginica"},
{"sepal_length":6,"sepal_width":2.2,"petal_length":5,"petal_width":1.5,"species":"virginica"},
{"sepal_length":6.9,"sepal_width":3.2,"petal_length":5.7,"petal_width":2.3,"species":"virginica"},
{"sepal_length":5.6,"sepal_width":2.8,"petal_length":4.9,"petal_width":2,"species":"virginica"},
{"sepal_length":7.7,"sepal_width":2.8,"petal_length":6.7,"petal_width":2,"species":"virginica"},
{"sepal_length":6.3,"sepal_width":2.7,"petal_length":4.9,"petal_width":1.8,"species":"virginica"},
{"sepal_length":6.7,"sepal_width":3.3,"petal_length":5.7,"petal_width":2.1,"species":"virginica"},
{"sepal_length":7.2,"sepal_width":3.2,"petal_length":6,"petal_width":1.8,"species":"virginica"},
{"sepal_length":6.2,"sepal_width":2.8,"petal_length":4.8,"petal_width":1.8,"species":"virginica"},
{"sepal_length":6.1,"sepal_width":3,"petal_length":4.9,"petal_width":1.8,"species":"virginica"},
{"sepal_length":6.4,"sepal_width":2.8,"petal_length":5.6,"petal_width":2.1,"species":"virginica"},
{"sepal_length":7.2,"sepal_width":3,"petal_length":5.8,"petal_width":1.6,"species":"virginica"},
{"sepal_length":7.9,"sepal_width":3.8,"petal_length":6.4,"petal_width":2,"species":"virginica"},
{"sepal_length":6.4,"sepal_width":2.8,"petal_length":5.6,"petal_width":2.2,"species":"virginica"},
{"sepal_length":6.3,"sepal_width":2.8,"petal_length":5.1,"petal_width":1.5,"species":"virginica"},
{"sepal_length":6.1,"sepal_width":2.6,"petal_length":5.6,"petal_width":1.4,"species":"virginica"},
{"sepal_length":7.7,"sepal_width":3,"petal_length":6.1,"petal_width":2.3,"species":"virginica"},
{"sepal_length":6.3,"sepal_width":3.4,"petal_length":5.6,"petal_width":2.4,"species":"virginica"},
{"sepal_length":6.4,"sepal_width":3.1,"petal_length":5.5,"petal_width":1.8,"species":"virginica"},
{"sepal_length":6,"sepal_width":3,"petal_length":4.8,"petal_width":1.8,"species":"virginica"},
{"sepal_length":6.9,"sepal_width":3.1,"petal_length":5.4,"petal_width":2.1,"species":"virginica"},
{"sepal_length":6.7,"sepal_width":3.1,"petal_length":5.6,"petal_width":2.4,"species":"virginica"},
{"sepal_length":6.9,"sepal_width":3.1,"petal_length":5.1,"petal_width":2.3,"species":"virginica"},
{"sepal_length":5.8,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.9,"species":"virginica"},
{"sepal_length":6.8,"sepal_width":3.2,"petal_length":5.9,"petal_width":2.3,"species":"virginica"},
{"sepal_length":6.7,"sepal_width":3.3,"petal_length":5.7,"petal_width":2.5,"species":"virginica"},
{"sepal_length":6.7,"sepal_width":3,"petal_length":5.2,"petal_width":2.3,"species":"virginica"},
{"sepal_length":6.3,"sepal_width":2.5,"petal_length":5,"petal_width":1.9,"species":"virginica"},
{"sepal_length":6.5,"sepal_width":3,"petal_length":5.2,"petal_width":2,"species":"virginica"},
{"sepal_length":6.2,"sepal_width":3.4,"petal_length":5.4,"petal_width":2.3,"species":"virginica"}]

其中,训练集包含 130 个项目,测试集包含 14 个。如果你看看这些数据是什么样子,你会看到

如下内容:

{
  "sepal_length": 5.1,
  "sepal_width": 3.5,
  "petal_length": 1.4,
  "petal_width": 0.2,
  "species": "setosa"
}

我们可以看到萼片和花瓣长度和宽度四个不同特征,以及物种的标签。

为了能够将它与 Tensorflow.js 一起使用,我们需要将这些数据塑造成框架能够理解的格式,在这种情况下,对于训练数据,它将是 [130, 4] 的 130 个样本,每个样本有四个特征。

import * as trainingSet from "training.json";
import * as testSet from "testing.json";
const trainingData = tf.tensor2d(
  trainingSet.map(item => [
    item.sepal_length,
    item.sepal_width,
    item.petal_length,
    item.petal_width
  ]),
  [130, 4]
);
const testData = tf.tensor2d(
  testSet.map(item => [
    item.sepal_length,
    item.sepal_width,
    item.petal_length,
    item.petal_width
  ]),
  [14, 4]
);

接下来,我们还需要对输出数据进行整形:

const output = tf.tensor2d(trainingSet.map(item => [
    item.species === 'setosa' ? 1 : 0,
    item.species === 'virginica' ? 1 : 0,
    item.species === 'versicolor' ? 1 : 0
]), [130,3])

然后,一旦我们的数据准备就绪,我们就可以继续创建模型:

const model = tf.sequential();
model.add(tf.layers.dense(
    {
        inputShape: 4,
        activation: 'sigmoid',
        units: 10
    }
));
model.add(tf.layers.dense(
    {
        inputShape: 10,
        units: 3,
        activation: 'softmax'
    }
));

在上面的代码示例中,我们首先实例化一个顺序模型,添加一个输入和输出层。

你可以看到内部使用的参数(inputShape, activation, and units)超出了本文的范围,因为它们可能会根据你创建的模型、使用的数据类型等而有所不同。

一旦我们的模型准备就绪,我们就可以使用我们的数据对其进行训练:

async function train_data(){
    for(let i=0;i<15;i++){
      const res = await model.fit(trainingData, outputData,{epochs: 40});
    }
}
async function main() {
  await train_data();
  model.predict(testSet).print();
}

如果这运作良好,你可以开始用自定义用户输入替换测试数据。

一旦我们调用我们的 main 函数,预测的输出将看起来像以下三个选项之一:

[1,0,0] // Setosa[0,1,0] // Virginica[0,0,1] // Versicolor

预测返回一个由三个数字组成的数组,表示数据属于三个类别之一的概率。 最接近 1 的数字是最高预测值。

例如,如果分类的输出为 [0.0002, 0.9494, 0.0503],则数组的第二个元素最高,因此模型预测新的输入很可能是 Virginica。

这就是 Tensorflow.js 中的简单神经网络!

我们只讨论了 Irises 的一个小数据集,但如果您想继续使用更大的数据集或处理图像,步骤将是相同的:

  • 收集数据;
  • 在训练集和测试集之间拆分;
  • 重新格式化数据以便 Tensorflow.js 可以理解它;
  • 选择你的算法;
  • 拟合数据;
  • 预测。

如果你想保存创建的模型以便能够在另一个应用程序中加载它并预测新数据,你可以使用以下行来执行此操作:

await model.save('file:///path/to/my-model'); // in Node.js

完整代码

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Tensorflow.js</title>
	<link rel="stylesheet" href="src/styles.css" rel="external nofollow" >
</head>
<body>
	<h1>使用 Tensorflow.js 在 JavaScript 中定义、训练和运行机器学习模型</h1>
	<section class="data-inputs">
		<h3>鸢尾花分类</h3>
		<p>正在训练中...</p>
		<p class="training-steps"></p>
		<div class="input-block">
			<label for="sepal-length">Sepal lenth:</label>
			<input name="sepal-length" type="number" min="0" max="100" placeholder="1.5">
		</div>
		<div class="input-block">
			<label for="sepal-width">Sepal width:</label>
			<input name="sepal-width" type="number" min="0" max="100" placeholder="0.4">
		</div>
		<div class="input-block">
			<label for="petal-length">Petal length:</label>
			<input name="petal-length" type="number" min="0" max="100" placeholder="1.0">
		</div>
		<div class="input-block">
			<label for="petal-width">Petal width:</label>
			<input name="petal-width" type="number" min="0" max="100" placeholder="0.7">
		</div>
		<button class="predict" disabled>预测</button>
	</section>
	<section class="prediction-block">
		<p>鸢尾花 预测:</p>
		<p class="prediction"></p>
	</section>
	<script src="src/index.js"></script>
</body>
</html>

index.js

import * as tf from "@tensorflow/tfjs";
import trainingSet from "./training.json";
import testSet from "./testing.json";
let trainingData, testingData, outputData, model;
let training = true;
let predictButton = document.getElementsByClassName("predict")[0];
const init = async () => {
  splitData();
  createModel();
  await trainData();
  if (!training) {
    predictButton.disabled = false;
    predictButton.onclick = () => {
      const inputData = getInputData();
      predict(inputData);
    };
  }
};
const splitData = () => {
  trainingData = tf.tensor2d(
    trainingSet.map(item => [
      item.sepal_length,
      item.sepal_width,
      item.petal_length,
      item.petal_width
    ]),
    [130, 4]
  );
  testingData = tf.tensor2d(
    testSet.map(item => [
      item.sepal_length,
      item.sepal_width,
      item.petal_length,
      item.petal_width
    ]),
    [14, 4]
  );
  outputData = tf.tensor2d(
    trainingSet.map(item => [
      item.species === "setosa" ? 1 : 0,
      item.species === "virginica" ? 1 : 0,
      item.species === "versicolor" ? 1 : 0
    ]),
    [130, 3]
  );
};
const createModel = () => {
  model = tf.sequential();
  model.add(
    tf.layers.dense({ inputShape: 4, activation: "sigmoid", units: 10 })
  );
  model.add(
    tf.layers.dense({
      inputShape: 10,
      units: 3,
      activation: "softmax"
    })
  );
  model.compile({
    loss: "categoricalCrossentropy",
    optimizer: tf.train.adam()
  });
};
const trainData = async () => {
  let numSteps = 15;
  let trainingStepsDiv = document.getElementsByClassName("training-steps")[0];
  for (let i = 0; i < numSteps; i++) {
    let res = await model.fit(trainingData, outputData, { epochs: 40 });
    trainingStepsDiv.innerHTML = `Training step: ${i}/${numSteps - 1}, loss: ${
      res.history.loss[0]
    }`;
    if (i === numSteps - 1) {
      training = false;
    }
  }
};
const predict = async inputData => {
  for (let [key, value] of Object.entries(inputData)) {
    inputData[key] = parseFloat(value);
  }
  inputData = [inputData];
  let newDataTensor = tf.tensor2d(
    inputData.map(item => [
      item.sepal_length,
      item.sepal_width,
      item.petal_length,
      item.petal_width
    ]),
    [1, 4]
  );
  let prediction = model.predict(newDataTensor);
  displayPrediction(prediction);
};
const getInputData = () => {
  let sepalLength = document.getElementsByName("sepal-length")[0].value;
  let sepalWidth = document.getElementsByName("sepal-width")[0].value;
  let petalLength = document.getElementsByName("petal-length")[0].value;
  let petalWidth = document.getElementsByName("petal-width")[0].value;
  return {
    sepal_length: sepalLength,
    sepal_width: sepalWidth,
    petal_length: petalLength,
    petal_width: petalWidth
  };
};
const displayPrediction = prediction => {
  let predictionDiv = document.getElementsByClassName("prediction")[0];
  let predictionSection = document.getElementsByClassName(
    "prediction-block"
  )[0];
  let maxProbability = Math.max(...prediction.dataSync());
  let predictionIndex = prediction.dataSync().indexOf(maxProbability);
  let irisPrediction;
  switch (predictionIndex) {
    case 0:
      irisPrediction = "Setosa";
      break;
    case 1:
      irisPrediction = "Virginica";
      break;
    case 2:
      irisPrediction = "Versicolor";
      break;
    default:
      irisPrediction = "";
      break;
  }
  predictionDiv.innerHTML = irisPrediction;
  predictionSection.style.display = "block";
};
init();

styles.css

body {
  font-family: "Avenir";
}
h1 {
  text-align: center;
  width: 80%;
  margin: 0 auto;
}
.data-inputs {
  display: block;
  width: 80%;
  margin: 0 auto;
}
.input-block {
  display: inline-block;
  width: fit-content;
  margin: 1em 0.5em 2em 0.5em;
}
.input-block:first-of-type {
  margin-left: 0;
}
.input-block input {
  width: 7em;
  height: 2em;
}
.input-block input::placeholder {
  color: rgba(0, 0, 0, 0.3);
}
button {
  display: block;
  padding: 0.5em 1em;
  border-radius: 5px;
  font-size: 14px;
}
.prediction-block {
  display: none;
  width: 80%;
  margin: 0 auto;
}

package.json

{
  "name": "Irises Classficaton",
  "version": "1.0.0",
  "description": "",
  "main": "index.html",
  "scripts": {
    "start": "parcel index.html --open",
    "build": "parcel build index.html"
  },
  "dependencies": {
    "@tensorflow/tfjs": "1.1.2"
  },
  "devDependencies": {
    "@babel/core": "7.2.0",
    "parcel-bundler": "^1.6.1"
  },
  "keywords": []
}

效果如下:

以上就是前端AI机器学习在浏览器中训练模型的详细内容,更多关于前端AI浏览器训练模型的资料请关注我们其它相关文章!

(0)

相关推荐

  • 聊聊那些使用前端Javascript实现的机器学习类库

    机器学习(Machine Learning)在最近几年绝对称的上是大火,越来越多的公司和资本投入了巨大资源和金钱到这个新上位的技术"新宠"中,尤其是随着更多的各种机器学习相关类库的出现和发展,更多新的技术已经被应用到了机器学习中, 现在大家可以看到, Python不再是唯一个老牌机器学习的必用语言, 对于现代神经网络(neural networks)语言不再是一个问题, 你基本可以使用任何的编程语言, 包括今天我们介绍的标准前端开发语言 - Javascript Web的整个体系已经在

  • Rainbond对前端项目Vue及React的持续部署

    目录 前言: 部署前检查 1.1 添加 nodestatic.json 文件 1.2 添加 web.conf 文件 1.3 源码部署Vue项目 常见问题 前言: 以往我们在部署 Vue.React 前端项目有几种方法: 项目打包好之后生成dist目录,将其放入nginx中,并进行相应的访问配置. 将项目打包好放入tomcat中. 将项目打包好的dist目录中的static和index.html文件放入springboot项目的resources目录下 直接运行一个前端server,类似本地开发那

  • ConstraintValidator类如何实现自定义注解校验前端传参

    前言 今天项目碰到这么一个问题,前端传递的json格式到我的微服务后端转换为vo类,其中有一个Integer的字段后端希望它在固定的几个数里面取值,例如只能取值1.2.4. 一般咱们的思路是啥呢,找一些spring为我们提供的类似@Length.@NotBlank这些注解加在参数上面. 像下面这样 不过我这个校验一时间想不起来用哪个注解了,咋整呢?行吧,咱不求人,自己实现一个. 补充一句话,千万别直接拿着实体类往后传递到service层校验哈,太low了这样子. 一.利用@Constraint定

  • 前端AI机器学习在浏览器中训练模型

    目录 识别鸢尾花 测试集: testing.json 训练集: training.json 完整代码 index.html index.js styles.css package.json 识别鸢尾花 本文将在浏览器中定义.训练和运行模型. 为了实现这一功能,我将构建一个识别鸢尾花的案例. 接下来,我们将创建一个神经网络.同时,根据开源数据集我们将鸢尾花分为三类:Setosa.Virginica 和 Versicolor. 每个机器学习项目的核心都是数据集. 我们需要采取的第一步是将这个数据集拆

  • 关于安卓手机微信浏览器中使用XMLHttpRequest 2上传图片显示字节数为0的解决办法

    前端JS中使用XMLHttpRequest 2上传图片到服务器,PC端和大部分手机上都正常,但在少部分安卓手机上上传失败,服务器上查看图片,显示字节数为0.下面是上传图片的核心代码: HTML <input type="file" id="choose" capture="camera" accept="image/*"> JavaScript var filechooser = document.getEleme

  • Nodejs中使用puppeteer控制浏览器中视频播放功能

    本项目主要功能为在浏览器中自动播放视频,并且实现音量控制,快进快退,全屏控制,播放暂停控制等功能. 仓库地址:  github.com/hapiman/chr- 安装静态服务器 如果电脑上存在nodejs的环境,可以直接安装 anywhere 来访问 index.html 页面. 进入项目根目录,执行命令: anywhere ,然后浏览器会自动打开 http://localhost:8000 页面. 使用puppeteer自动化执行命令 通过在 nodejs 调用前端页面的方法,然后能够Sock

  • vue 解决在微信内置浏览器中调用支付宝支付的情况

    我的思路大概是这样的 1. 验证是否是在微信内置浏览器中调用支付宝 2.给支付页面的url加上调用接口所需的参数(因为在微信里是不能直接调用支付宝的需要调用外部浏览器) 3.在外部浏览器中完成支付跳转页面 第一步: payment: 是选择支付页面,pay-mask是用于在微信内置浏览器中调用支付宝的中间页 payment主要代码: let ua = window.navigator.userAgent.toLowerCase() ua.match(/MicroMessenger/i) == "

  • Vue Element前端应用开发之Vuex中的API Store View的使用

    概述 在我们开发Vue应用的时候,很多时候需要记录一些变量的内容,这些可以用来做界面状态的承载,也可以作为页面间交换数据的处理,处理这些内容可以归为Vuex的状态控制.例如我们往往前端需要访问后端数据,一般是通过封装的Web API调用获取数据,而使用Store模式来处理相关的数据或者状态的变化,而视图View主要就是界面的展示处理.本篇随笔主要介绍如何整合这三者之间的关系,实现数据的获取.处理.展示等逻辑操作. Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管

  • 浏览器中视频播放器实现的基本思路与代码

    目录 前言 浏览器中的音视频知识总结 视频编码 封装格式 音视频标签 常用属性 常用事件 常用方法 整体思路如下 代码实现 总结 前言 自定义个播放器,组件都是用的原生的,所以有点丑,重点关注业务逻辑吧. 界面大概长下面这个样子. 大家可以看着界面,在脑海中想一下自己会如何实现这个视频播放器.可以问自己以下几个问题: 这个组件会接受那些props 如何获取视频的基本信息,包括时长,分辨率等 暂停.播放如何实现 拖动进度条的逻辑如何实现 视频初始加载显示loading如何处理 视频播放过程中卡顿显

  • 在浏览器中实现图片粘贴的jQuery插件-- pasteimg使用指南

    pasteimg是一款可以在浏览器中实现图片粘贴的jQuery插件,兼容Chrome.Firefox.IE11以及其他使用这些内核的浏览器,比如,国内著名的360浏览器. pasteimg可以识别浏览器中直接复制的图片,也可以识别复制的富文本中的图片.仅仅可以识别在浏览器中复制的内容,操作系统中复制的图片是不能识别的. pasteimg依赖jQuery,简单易用,引入jQuery和paste.image.js后,调用方式如下: 复制代码 代码如下: //在需要监听粘贴事件的dom元素上调用pas

  • 事件模型在各浏览器中存在差异

    标准参考 根据 W3C DOM 2 Events 描述,EventTarget 接口被所有支持 DOM 事件模型的节点(Node)实现. 该接口提供了 'addEventListener' 和 'removeEventListener' 方法,用来绑定或解绑一个 EventListeners 接口到一个 EventTarget. DOM 2 Events 中定义了 Event 接口,用来提供事件的上下文信息,它提供了若干标准属性和方法. 实现 Event 接口的对象一般作为第一个参数传入事件处理

  • VBScript 剪贴板抓取URL并在浏览器中打开

    您好,CL.这是很有趣的问题,或者我们应当说,这是两个很有趣的问题.因为您实际上问了两个问题.第一个问题很简单:我可以使用脚本打开特定的 Web 站点吗?您大概已经知道答案了,我可以大声地回答您,可以!下面是一个示例脚本,它将"脚本中心"的 URL 存储在一个名为 strURL 的变量中.然后,此脚本会创建 WSH Shell 对象的一个实例,并使用 Run 方法来打开默认的 Web 浏览器并导航到指定的 URL: strURL = "http://www.microsoft

  • Visual Studio 2017中找回消失的“在浏览器中查看”命令

    不知为何,在新安装 Visual Studio 2017 后,发现所有 Web 项目上右键菜单的"在浏览器中查看"命令消失了,只能以调试模式启动网站,非常别扭. 最后在 Stackoverflow 上找到了遇到同样问题的解决方法:通过自定义菜单将此命令添加回来. 1.在工具栏上右键,选择"自定义": 2.在弹出的窗口中,选择"命令"标签.然后选择"上下文菜单",在其右侧下拉列表中找到"项目和解决方案上下文菜单 | 项

随机推荐