【问题标题】:Tensorflow.js LSTM time series predictionTensorflow.js LSTM 时间序列预测
【发布时间】:2018-11-16 15:04:00
【问题描述】:

我正在尝试使用 LSTM RNN 在 Tensorflow.js 中构建一个简单的时间序列预测脚本。我显然是 ML 的新手。我一直在尝试从 Keras RNN/LSTM 层 api 改编我的 JS 代码,这显然是一回事。从我收集的图层来看,形状等都是正确的。有什么想法我在这里做错了吗?

async function predictfuture(){

    ////////////////////////
    // create fake data
    ///////////////////////

    var xs = tf.tensor3d([
        [[1],[1],[0]],
        [[1],[1],[0]],
        [[1],[1],[0]],
        [[1],[1],[0]],
        [[1],[1],[0]],
        [[1],[1],[0]]
    ]);
    xs.print();

    var ys = tf.tensor3d([
        [[1],[1],[0]],
        [[1],[1],[0]],
        [[1],[1],[0]],
        [[1],[1],[0]],
        [[1],[1],[0]],
        [[1],[1],[0]]
    ]);
    ys.print();


    ////////////////////////
    // create model w/ layers api
    ///////////////////////

    console.log('Creating Model...');

    /*

    model design:

                    i(xs)   h       o(ys)
    batch_size  ->  *       *       * -> batch_size
    timesteps   ->  *       *       * -> timesteps
    input_dim   ->  *       *       * -> input_dim


    */

    const model = tf.sequential();

    //hidden layer
    const hidden = tf.layers.lstm({
        units: 3,
        activation: 'sigmoid',
        inputShape: [3 , 1]
    });
    model.add(hidden);

    //output layer
    const output = tf.layers.lstm({
        units: 3,
        activation: 'sigmoid',
        inputShape: [3] //optional
    });
    model.add(output);

    //compile
    const sgdoptimizer = tf.train.sgd(0.1)
    model.compile({
        optimizer: sgdoptimizer,
        loss: tf.losses.meanSquaredError
    });

    ////////////////////////
    // train & predict
    ///////////////////////

    console.log('Training Model...');

    await model.fit(xs, ys, { epochs: 200 }).then(() => {

        console.log('Training Complete!');
        console.log('Creating Prediction...');

        const inputs = tf.tensor2d( [[1],[1],[0]] );
        let outputs = model.predict(inputs);
        outputs.print();

    });

}

predictfuture();

我的错误:

【问题讨论】:

  • 据我了解,张量流中的 LSTM 总是需要一个额外的维度来反映这些步骤。所以const inputs = tf.tensor3d( [[[1],[1],[0]]] ); 是我的猜测
  • 不错,但不幸的是仍然遇到同样的错误。

标签: javascript tensorflow lstm rnn tensorflow.js


【解决方案1】:

代码通过添加 returnSequences: true 并将输出层单位更改为 1 来运行:

//hidden layer
const hidden = tf.layers.lstm({
    units: 3,
    activation: 'sigmoid',
    inputShape: [3 , 1],
    returnSequences: true
});
model.add(hidden);

//output layer
const output = tf.layers.lstm({
    units: 1, 
    activation: 'sigmoid',
    returnSequences: true
})
model.add(output);

正如@Sebastian Speitel 所说,将输入更改为:

const inputs = tf.tensor3d( [[[1],[1],[0]]] );

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2017-10-03
    • 2020-07-21
    • 2021-09-30
    相关资源
    最近更新 更多