Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow.js LSTM time series prediction

I am trying to build a simple time-series prediction script in Tensorflow.js with an LSTM RNN. I am new to ML obviously. I have been trying to adapt my JS code from the Keras RNN/LSTM layer api which apparently is the same thing. From what I gather my layer, shapes etc are all correct. Any thoughts on what I am doing wrong here?

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();

And my error:

enter image description here

like image 499
barrylachapelle Avatar asked Mar 07 '23 01:03

barrylachapelle


1 Answers

The code runs by adding returnSequences: true and changing the output layer units to 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);

And as @Sebastian Speitel mentions, change the input to:

const inputs = tf.tensor3d( [[[1],[1],[0]]] );
like image 97
Chris Buck Avatar answered Mar 14 '23 19:03

Chris Buck