tensorflow.js getting Error when checking input: expected dense_Dense1_input to have 3 dimension(s). but got array with shape

Viewed 589

simple question and im sure answer is straightforward but im really struggling to match model shape with tensor fitting into model.

this simple code

    let tf = require('@tensorflow/tfjs-node');

    let features = {
        x: [1,2,3,4,5,6,7,8,9],
        y: [1,2,3,4,5,6,7,8,9]
      }

    let tensorfeature  = tf.tensor2d(Object.values(features))

    console.log(tensorfeature.shape)

    const model = tf.sequential();
        model.add(tf.layers.dense(
            {
            inputShape: tensorfeature.shape,
            units: 1
        }
            ))
            const optimizer = tf.train.sgd(0.005);
            model.compile({optimizer: optimizer, loss: 'meanAbsoluteError'}); 
            model.fit(tensorfeature,
                {epochs: 5}
                )

Results in Error: Error when checking input: expected dense_Dense1_input to have 3 dimension(s). but got array with shape 2,9

tried multiple things with reshape, slice, etc with no luck. Can someone point me what exactly is wrong?

1 Answers

model.fit takes at least two parameters x, y which are either tensors or array of tensors. The config object is the third parameter.

Also, the feature(tensorfeature) tensor passed as argument to model.fit should be one dimension higher than the inputShape of the model. Since tensorfeature.shape is used as the inputShape, if we want to traing the model with tensorfeature its dimension should be expanded. It can be done using reshape or expandDims.

model.fit(tensorfeature.expandDims(0))
// or possibly
model.fit(tensorfeature.reshape([1, ...tensorfeature.shape])

This shape mismatch between the model and the training data has been discussed here and there

Related