Tensorflow.js LSTM 时间序列预测

Tensorflow.js LSTM time series prediction

我正在尝试使用 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();

而我的错误:

代码通过添加 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]]] );