Search code examples
pythontensorflowkeraskeras-layerkeras-2

Why deleting one dimension in tensor causes InvalidArgumentError: Matrix size-incompatible?


Part of my codes:

reshape_out = Reshape((3, 21, 1), input_shape=(21*3,), name='reshape_to_3_21')(output3d)
drop_out = Lambda(lambda x:x[0:2, :, :], output_shape=(2, 21, 1), name='projection')(reshape_out)
flatten_out = Flatten()(drop_out)

I got the following error:

InvalidArgumentError: Matrix size-incompatible: In[0]: [2,63], In[1]: [42,1024].

But if

drop_out = Lambda(lambda x:x[0:2, :, :], output_shape=(2, 21, 1), name='projection')(reshape_out)

is removed, everything is OK. Why?


Solution

  • First axis is the batch axis and it seems you are mistakenly slicing it instead of the second axis:

    def drop_output_shape(shp):
        return (shp[0], 2) + shp[2:]
    
    drop_out = Lambda(lambda x: x[:, 0:2, :, :], 
                      output_shape=drop_output_shape, name='projection')(reshape_out)