· Use TensorFlowJS to fit the curve

  • Y = x* x-2x +3 + 0.1(random value from -1 to 1) curve given x range (0,3)
  • In the straight line fitting blog, we successfully fitted a straight line using the simplest y=wx+b model, and now we are further fitting the curve. The simple y=wx+ B model can no longer meet our needs, and more neurons are needed to solve the problem.
  • code
<html>

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

</head>

<body>
  <button class="btn btn-primary" onclick="fnRun0();">Began to 0</button>
  <div id="p0Id">out0</div>
  <button class="btn btn-primary" onclick="fnRun1();">Began to 1</button>
  <div id="p1Id">out1</div>
  <button class="btn btn-primary" onclick="fnRun2();">Start 2</button>
  <div id="p2Id">out2</div>
</body>

<script>
  function get_ys(xs) {
    var ys = new Array(a);for (var i = 0; i < xs.length; i++) {
      ys[i] = xs[i] * xs[i] - 2 * xs[i] + 3 + (0.001 * (2 * Math.random() - 1));
    }
    return (ys);
  }
  var xs = new Array(a);for (var i = 0; i < 200; i++) {
    xs[i] = 0.01 * i;
  }
  var ys = get_ys(xs);
  const xst = tf.tensor(xs, [xs.length, 1]);
  const yst = tf.tensor(ys, [ys.length, 1]);
  const a = tf.variable(tf.scalar(Math.random()));
  const b = tf.variable(tf.scalar(Math.random()));
  const c = tf.variable(tf.scalar(Math.random()));

  function predict(x) {
    return tf.tidy(() = > {
      return a.mul(x.square())
        .add(b.mul(x))
        .add(c);
    });
  }

  function loss(prediction, labels) {
    const error = prediction.sub(labels).square().mean();
    return error;
  }
  const numIterations = 1000;
  const learningRate = 0.12;
  
  const optimizer = tf.train.sgd(learningRate);

  
  function train(xst, yst, numIterations) {
    for (var iter = 0; iter < numIterations+1; iter++) {

      optimizer.minimize(() = > {
        const predsYs = predict(xst);
        if(iter%100= =0) {console.log(iter+" steps loss is "+loss(predsYs, yst));
        }
        return loss(predsYs, yst);
      });
    }
    const test_xs = tf.tensor([0.5.1.1.5], [3.1]);
    predict(test_xs).print();
  }
  train(xst,yst,numIterations);
  
</script>

</html>
Copy the code
  • Output results after 1000 rounds of training, we input [0.5,1,1.5] for prediction, and the obtained results are [[2.2503195], [2.0105994], [2.2543631]], which fit the curve well.

log

"0 Steps Loss is Tensor 1.7456094026565552" "100 Steps Loss is Tensor 0.08455191552639008" "200 Steps Loss is Tensor 0.04024720191919555664 ""300 Steps Loss is Tensor 0.0191580131649971" "400 Steps Loss is Tensor 0.009119458496570587" "500 Steps Loss is Tensor 0.004341088235378265" "600 Steps Loss is Tensor 0.0020665652118623257" "700 Steps Loss is Tensor 0.0009838765254244208" "800 Steps loss is Tensor 0.0004685141902882606" "900 Steps Loss is Tensor 0.00022319876006804407" "1000 Steps Loss is Tensor 0.00010642936103977263" "Tensor [[2.2503195], [2.0105994], [2.2543631]]. ""Copy the code