简介

XOR (异或)逻辑回归

预测概率

输入[x,y] 预测分布在0、还是 1

操作步骤

1、引入数据集

引自 playground 源码
会生成 [{x:-1, y: -2, label: 0}, {x:1, y: 2, label: 1}] 这样的数据结构

  1. export function getData(numSamples) {
  2. let points = [];
  3. function genGauss(cx, cy, label) {
  4. for (let i = 0; i < numSamples / 2; i++) {
  5. let x = normalRandom(cx);
  6. let y = normalRandom(cy);
  7. points.push({ x, y, label });
  8. }
  9. }
  10. genGauss(2, 2, 0);
  11. genGauss(-2, -2, 0);
  12. genGauss(-2, 2, 1);
  13. genGauss(2, -2, 1);
  14. return points;
  15. }
  16. /**
  17. * Samples from a normal distribution. Uses the seedrandom library as the
  18. * random generator.
  19. *
  20. * @param mean The mean. Default is 0.
  21. * @param variance The variance. Default is 1.
  22. */
  23. function normalRandom(mean = 0, variance = 1) {
  24. let v1, v2, s;
  25. do {
  26. v1 = 2 * Math.random() - 1;
  27. v2 = 2 * Math.random() - 1;
  28. s = v1 * v1 + v2 * v2;
  29. } while (s > 1);
  30. let result = Math.sqrt(-2 * Math.log(s) / s) * v1;
  31. return mean + Math.sqrt(variance) * result;
  32. }

2、可视化数据集

WechatIMG434.jpeg

3、创建模型、添加层、训练、训练结果

  1. import * as tf from '@tensorflow/tfjs'
  2. import * as tfvis from '@tensorflow/tfjs-vis'
  3. import { getData } from './data'
  4. window.onload = async () => {
  5. const data = getData(400)
  6. // 可视化数据集
  7. tfvis.render.scatterplot({
  8. name: 'XOR逻辑回归训练数据'
  9. },{
  10. values: [
  11. data.filter(p => p.label === 1), // 分类为1 的数组
  12. data.filter(p => p.label === 0) // 分类为0 的数组
  13. ] // 这里是嵌套数组,来渲染不同颜色的点
  14. })
  15. // 定义多层神经网络
  16. const model = tf.sequential()
  17. // 添加第一层
  18. model.add(tf.layers.dense(
  19. {
  20. units: 4, // 神经元个数
  21. inputShape: [2], // 数据特征是[x,y]
  22. activation: 'relu'
  23. }
  24. ))
  25. // 添加第二层 (第二层会继承第一层的入参)
  26. model.add(tf.layers.dense({
  27. units: 1, // 这里是一个,因为只需要输出一个概率
  28. activation: 'sigmoid' // 输出0-1的概率
  29. }))
  30. model.compile({
  31. loss: tf.losses.logLoss,
  32. optimizer: tf.train.adam(0.1)
  33. })
  34. const inputs = tf.tensor(data.map(p => [p.x,p.y]))
  35. const label = tf.tensor(data.map(p => p.label))
  36. await model.fit(inputs, label, {
  37. epochs: 10,
  38. callbacks: tfvis.show.fitCallbacks({
  39. name: '训练效果'
  40. }, ['loss'])
  41. })
  42. window.predict = (form) => {
  43. const pred = model.predict(tf.tensor([[form.x.value*1, form.y.value*1]])) // * 1转化成数字
  44. alert(`预测结果${pred.dataSync()[0]}`)
  45. }
  46. }

总结: 与此前单一神经元不同的是,多层神经元要添加多层,以来解决复杂的问题