Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras Reshape layer adding an extra dimension?

The Reshape layer is not working how I would expect. In the example below, I think the last line should return a tensor object of shape [5,1]. However an error is thrown, stating that a shape [5] tensor cannot be reshaped into a size [5,5,1] tensor.

>>> from keras.layers import Reshape
>>> from keras import backend as K
>>> import numpy as np
>>> x = K.constant(np.array([1,2,3,4,5]))
>>> K.eval(x)
array([1., 2., 3., 4., 5.], dtype=float32)
>>> Reshape(target_shape=(5,1))(x)
...
ValueError: Cannot reshape a tensor with 5 elements to
shape [5,5,1] (25 elements) for 'reshape_3/Reshape' (op: 
'Reshape') with input shapes: [5], [3] and with input 
tensors computed as partial shapes: input[1] = [5,5,1].

Can someone kindly explain how the Reshape layer works (i.e. why it's adding the extra dim) and how to do the process of reshaping a vector into a matrix?

Thanks

like image 346
littlebenlittle Avatar asked Aug 09 '18 22:08

littlebenlittle


People also ask

How do you reshape a keras layer?

Reshape class Layer that reshapes inputs into the given shape. Arbitrary, although all dimensions in the input shape must be known/fixed. Use the keyword argument input_shape (tuple of integers, does not include the samples/batch size axis) when using this layer as the first layer in a model.

What does Permute layer do?

Permutes the dimensions of the input according to a given pattern. Useful e.g. connecting RNNs and convnets.

What is TF keras layers flatten?

Advertisements. Flatten is used to flatten the input. For example, if flatten is applied to layer having input shape as (batch_size, 2,2), then the output shape of the layer will be (batch_size, 4) Flatten has one argument as follows keras.layers.Flatten(data_format = None)

How does keras define input shape?

The input shape In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data. Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3) .


1 Answers

User Reshape(target_shape=(1,))(x)

The batch_size is implied in the entire model and ignored from the beginning to the end.

If you do want to access the batch size, use a K.reshape(x,(5,1)).

Keras is not supposed to be used without creating a model made entirely of layers.

like image 137
Daniel Möller Avatar answered Oct 04 '22 22:10

Daniel Möller