[TensorFlowJS只如初见]实战四·使用TensorFlowJS拟合曲线(类似TensorFlow原生实现方法)

[TensorFlowJS只如初见]实战四·使用TensorFlowJS拟合曲线(类似TensorFlow原生实现方法)

  • 问题描述
    拟合y= x*x -2x +3 + 0.1(-1到1的随机值) 曲线
    给定x范围(0,3)

  • 问题分析
    在直线拟合博客中,我们使用最简单的y=wx+b的模型成功拟合了一条直线,现在我们在进一步进行曲线的拟合。简单的y=wx+b模型已经无法满足我们的需求,需要利用更多的神经元来解决问题了。

  • 代码

<html>

<head>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs">
  script>

head>

<body>
  <button class="btn btn-primary" onclick="fnRun0();">开始0button>
  <div id="p0Id">out0div>
  <button class="btn btn-primary" onclick="fnRun1();">开始1button>
  <div id="p1Id">out1div>
  <button class="btn btn-primary" onclick="learnLinear();">开始2button>
  <div id="p2Id">out2div>
body>

<script>
  //document.getElementById("p0Id").innerHTML = 0;
  function get_ys(xs) {
    var ys = new Array();
    for (var i = 0; i < xs.length; i++) {
      ys[i] = xs[i] * xs[i] - 2 * xs[i] + 3 + (0.1 * (2 * Math.random() - 1));
    }
    return (ys);
  }
  var xs = new Array();
  for (var i = 0; i < 100; i++) {
    xs[i] = 0.02 * i;
  }
  var ys = get_ys(xs);
  const xst = tf.tensor(xs, [xs.length, 1]);
  const yst = tf.tensor(ys, [ys.length, 1]);

  function get_weights(shape) {
    return (tf.variable(tf.randomNormal(shape)));
  }

  function get_bais(shape) {
    return (tf.variable(tf.fill(shape, 0.1)));
  }
  const w1 = get_weights([1, 10]);
  const w2 = get_weights([10, 1]);
  const b1 = get_bais([1, 10]);
  const b2 = get_bais([1, 1]);

  function predict(x) {
    return tf.tidy(() => {
      const l1 = tf.elu(tf.add(tf.matMul(x, w1), b1)); //不支持运算符重载 tf.add() 不能写成 +
      const y = tf.add(tf.matMul(l1, w2), b2);
      return y;
    });
  }

  function loss(predictions, labels) {
    // 将labels(实际的值)进行抽象
    // 然后获取平均数.
    return tf.tidy(() => {
      const meanSquareError = tf.mean(tf.square(tf.sub(predictions, labels)));
      return meanSquareError;
    });
  }
  const learningRate = 1;
  const optimizer = tf.train.adagrad(learningRate);
  const numIterations = 1001;

  function training() {
    for (var iter = 0; iter < numIterations; iter++) {
      optimizer.minimize(() => {
        const loss_var = loss(predict(xst), yst);
        if(iter % 100 ==0)
          loss_var.print();
        return loss_var;
      })
    }
  }

  training();
  const text_xs = tf.tensor([0,1,3], [3, 1]);
  predict(text_xs).print();
script>

html>
  • 输出结果
    进行1000轮训练以后,我们输入[0,1,3]进行预测,得到结果为
    [[2.9647527],
    [1.9793538],
    [3.9484348]]
    较好地拟合了曲线。

log

"Tensor
    4.915620803833008"
"Tensor
    0.018092654645442963"
"Tensor
    0.01064694207161665"
"Tensor
    0.008950537070631981"
"Tensor
    0.008051211014389992"
"Tensor
    0.007439687382429838"
"Tensor
    0.006973605137318373"
"Tensor
    0.006602670066058636"
"Tensor
    0.006299363449215889"
"Tensor
    0.0060538649559021"
"Tensor
    0.005853266455233097"
"Tensor
    [[2.9647527],
     [1.9793538],
     [3.9484348]]"

你可能感兴趣的:(深度学习,TensorFlowJS,TensorFlow)