Search code examples
tensorflowtensorflow.jstensorflowjs-converter

What does a -1 mean in the shape of a tensor input?


I've got a TensorFlowJS model that has an input that looks like this:

{"name":"dense_3_input","shape":[-1,25],"dtype":"float32"}

What does the -1 mean?

The way the model is constructed is using Dense(1, input_dim=25, activation="sigmoid") so I don't know where the -1 is coming from or how to properly create the tensor that it's looking for.

If I pass a tensor of

tf.tensor([0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1])

I get this error.

Error: The shape of dict['dense_3_input'] provided in model.execute(dict) must be [-1,25], but was [25]

The model works correctly in python when passed the above input of 25 0/1's. Did the conversion to a TensorFlowJS model not work correctly? Any insight would be greatly appreciated.


Solution

  • -1 in a dimension of a tensor means that that dimension's size will be computed as regard the other dimensions. The tensor shape should be a multiple of the product of the size of the other dimensions for it to work

    tensor size: 25, shape [-1, 25] => [1, 25]
    
                     shape [-1, 5] => [5, 5]
    
                     shape [-1, 3] => will not work
    

    It is useful when we don't know the size of the tensor but know that it will be a multiple of some values.

    In the example of the question, the initial tensor can be reshaped:

    • tf.tensor([0, 1...]).reshape([-1, 25]) or

    • it can be constructed directly as a 2d tensor tf.tensor([[0, 1...]])