JavaScript之机器学习3:Tensorflow.js 逻辑回归操作

逻辑回归操作

  1. 使用预先准备好的脚本生成二分类数据集
  2. 可视化二分类数据集
  3. 定义模型结构:带有激活函数的单个神经元
    • 初始化一个神经网络模型
    • 为神经网络模型添加层
    • 设计层的神经元个数,inputShape,激活函数
  4. 训练模型并可视化训练过程
    • 将训练数据转为Tensor
    • 训练模型
    • 使用tfvis可视化训练过程
  5. 进行预测
    • 编写前端界面输入待预测数据
    • 使用训练好的模型进行预测
    • 将输出的Tensor转为普通数据显示
      在这里插入图片描述
      在这里插入图片描述
      在这里插入图片描述
      演示代码:
<!-- index.html  -->
<form action="" onsubmit="predict(this);return false;">
    x: <input type="text" name="x">
    y: <input type="text" name="y">
    <button type="submit">预测</button>
</form>
// index.js
import * as tf from '@tensorflow/tfjs';
import * as tfvis from '@tensorflow/tfjs-vis';
import { getData } from './data.js';
window.onload = async() => {
    // 1. 使用预先准备好的脚本生成二分类数据集
    const data = getData(400);  // 获取400个点
    console.log(data);

    // 2. 可视化二分类数据集
    tfvis.render.scatterplot(
        {name:'逻辑回归训练数据'},
        {
            values: [
                data.filter(p => p.label === 1),
                data.filter(p => p.label === 0)
            ]
        }
    );

    // 3.定义模型结构:带有激活函数的单个神经元
    const model = tf.sequential(); // sequential 连续的
    model.add(tf.layers.dense({   // 添加全连接层 output = activation(dot(input, kernel) + bias)
        units: 1, // 1个神经元
        inputShape: [2],
        activation: 'sigmoid'  // 激活函数,sigmoid作用:把输出值压缩到0-1之间
    })); 
    // 设置损失函数和优化器
    model.compile({loss: tf.losses.logLoss, optimizer: tf.train.adam(0.1)});

    // 4. 训练模型并可视化训练过程
    const inputs = tf.tensor(data.map(p=>[p.x,p.y]));
    const labels = tf.tensor(data.map(p => p.label));

    await model.fit(inputs, labels, {
        batchSize: 40,
        epochs: 20,
        callbacks: tfvis.show.fitCallbacks(
            { name: '训练效果' },
            ['loss']
        )
    });

    window.predict = (form) => {
        const pred = model.predict(tf.tensor([[form.x.value*1, form.y.value*1]]));
        alert(`预测结果:${pred.dataSync()[0]}`)
    }
};
// data.js
export function getData(numSamples) {
    let points = [];
  
    function genGauss(cx, cy, label) {
      for (let i = 0; i < numSamples / 2; i++) {
        let x = normalRandom(cx);
        let y = normalRandom(cy);
        points.push({ x, y, label });
      }
    }
  
    genGauss(2, 2, 1);
    genGauss(-2, -2, 0);
    return points;
  }
  
  /**
   * Samples from a normal distribution. Uses the seedrandom library as the
   * random generator.
   *
   * @param mean The mean. Default is 0.
   * @param variance The variance. Default is 1. 设的越大,范围越广
   */
  function normalRandom(mean = 0, variance = 1) {
    let v1, v2, s;
    do {
      v1 = 2 * Math.random() - 1;
      v2 = 2 * Math.random() - 1;
      s = v1 * v1 + v2 * v2;
    } while (s > 1);
  
    let result = Math.sqrt(-2 * Math.log(s) / s) * v1;
    return mean + Math.sqrt(variance) * result;
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章