【问题标题】:Tensorflow.js: Simple linear regression not working greatTensorflow.js:简单的线性回归效果不佳
【发布时间】:2019-07-02 15:14:02
【问题描述】:

我有来自example video 的基本代码(视频的前半部分是这样做的,但使用了不同的数据集)。

代码:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
        <title>Website</title>
        <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>
        <style>

        </style>
        <script>
            var linearModel = tf.sequential();
            linearModel.add(tf.layers.dense({units: 1, inputShape: [1]}));
            linearModel.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

            var xs = tf.tensor1d([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]);
            var ys = tf.tensor1d([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]);

            linearModel.fit(xs, ys);

            function linearPrediction(val) {
                var output = linearModel.predict(tf.tensor2d([val], [1,1]));
                var prediction = Array.from(output.dataSync())[0];
                console.log(prediction);
            }

            linearPrediction(50);
        </script>
    </head>
    <body>
        Welcome to my website.
    </body>
</html>

我使用100 值训练它,其中输入与输出相同。然后,当我在训练后尝试使用50 作为输入运行它时,我得到的结果范围从-5060

这是正常现象吗?我希望值接近50

此外,当我使用值从 11000 的数组进行训练并输入 500 时,我什至会得到从 -600 开始的输出。

【问题讨论】:

    标签: javascript tensorflow machine-learning neural-network tensorflow.js


    【解决方案1】:

    您的代码中有两个主要问题。

    问题 1:不等待 Promise 完成

    linearModel.fit 返回一个 Promise,在训练完成后将被解决。这意味着,现在,模型将开始训练,但在训练完成之前,您已经要求进行预测。

    您必须等待 Promise 解决。最简单的方法是将您的代码放入async 函数并像这样使用await

    (async () => {
      var linearModel = tf.sequential();
      // ...
      await linearModel.fit(xs, ys);
      // ...
    })();
    

    问题 2:学习率不好

    sgd 的默认学习率是0.01,在您的情况下这太高了。使用该值训练模型增加了每次训练迭代的loss 值,这表明学习率很高。如果您想了解有关该主题的更多信息,请查看"estimating an optimal learning rate" 上的本指南。

    您可以通过使用tf.train.sgd 函数(而不是使用字符串)并传递如下所示的学习率来更改学习率:

    linearModel.compile({ loss: 'meanSquaredError', optimizer: tf.train.sgd(0.0001) });
    

    进一步改进:训练不止一个 epoch

    虽然上述提示应该已经产生接近50 的结果,但您可以通过训练多个时期来进一步改进您的模型。你可以像这样传递epochs 参数来训练你的模型更长时间:

    await linearModel.fit(xs, ys, {
      epochs: 10
    });
    

    自己试试

    我在下面的 sn-p 中添加了对您的代码的改进。您可以更改epochslearning rate 的值,看看它如何影响50 的结果预测。

    document.querySelector('button').addEventListener('click', async () => {
        const learningRate = document.querySelector('#learning_rate').value;
        const epochs = document.querySelector('#epochs').value;
        
        const linearModel = tf.sequential();
        linearModel.add(tf.layers.dense({ units: 1, inputShape: [1] }));
        linearModel.compile({ loss: 'meanSquaredError', optimizer: tf.train.sgd(learningRate) });
    
        const xs = tf.tensor1d([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]);
        const ys = tf.tensor1d([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]);
    
        await linearModel.fit(xs, ys, {
            epochs,
            callbacks: {
                onEpochEnd: (epoch, logs) => console.log(`Loss, epoch ${epoch}: ${logs.loss}`),
            },
        });
    
        function linearPrediction(val) {
            const output = linearModel.predict(tf.tensor1d([val]));
            const prediction = Array.from(output.dataSync())[0];
            console.log(`Prediction for 50: ${prediction}`);
        }
    
        linearPrediction(50);
    });
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>
    
    epochs: <input type="number" id="epochs" value="1" />
    learning rate: <input type="number" id="learning_rate" value="0.0001" />
    <button id="train">Train</button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2021-09-14
      • 2016-04-14
      • 1970-01-01
      • 2014-05-04
      • 2013-03-15
      • 2018-12-13
      相关资源
      最近更新 更多