使用TensorFlowJS进行简单的线性回归

时间:2018-06-26 13:15:10

标签: javascript tensorflow tensorflow.js

我正在尝试对项目进行一些线性回归。 因为我已经习惯了Javascript,所以我决定尝试使用TensorFlowJS。

我正在关注他们网站上的教程,并观看了一些解释其工作原理的视频,但是我仍然不明白为什么我的算法不能返回预期的结果。

这是我在做什么:

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.
const xs = tf.tensor1d([1, 2, 3, 4]);
const ys = tf.tensor1d([1, 2, 3, 4]);

// Train the model using the data.
model.fit(xs, ys).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  // Open the browser devtools to see the output
  const output = model.predict(tf.tensor2d([5], [1,1]));
  console.log(Array.from(output.dataSync())[0]);
});

我在这里尝试制作线性图,其中输入应始终等于输出。

我试图预测输入5会得到什么,但是看来输出是随机的。

它在Codepen上,因此您可以尝试:https://codepen.io/anon/pen/RJJNeO?editors=0011

2 个答案:

答案 0 :(得分:0)

您的训练数据需要比模型形状多一维,以反映训练批次。因此x和y必须至少为2D。

答案 1 :(得分:0)

您的模型仅在一个纪元(一个周期的训练)后即可进行预测。结果,损失仍然很大,导致预测不准确。

该模型的权重是随机初始化的。因此,只有一个时期,预测是非常随机的。这就是为什么,一个人需要训练一个以上的时期,或者在每批之后都更新重量(这里您也只有一批)。 要查看训练过程中的损失,您可以通过以下方式更改健身方法:

model.fit(xs, ys, { 
  callbacks: {
      onEpochEnd: (epoch, log) => {
        // display loss
        console.log(epoch, log.loss);
      }
    }}).then(() => {
  // make the prediction after one epoch
})

要获得准确的预测,您可以增加时期数

 model.fit(xs, ys, {
      epochs: 50,  
      callbacks: {
          onEpochEnd: (epoch, log) => {
            // display loss
            console.log(epoch, log.loss);
          }
        }}).then(() => {
      // make the prediction after one epoch
    })

这是一个片段,显示了增加时期数将如何帮助模型表现良好

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.
const xs = tf.tensor1d([1, 2, 3, 4]);
const ys = tf.tensor1d([1, 2, 3, 4]);

// Train the model using the data.
model.fit(xs, ys, {
  epochs: 50,
  callbacks: {
      onEpochEnd: (epoch, log) => {
        console.log(epoch, log.loss);
      }
    }}).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  // Open the browser devtools to see the output
  const output = model.predict(tf.tensor2d([6], [1,1]));
  output.print();
});
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
  </head>

  <body>
  </body>
</html>

相关问题