littlebenlittle
littlebenlittle

Reputation: 853

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

Upvotes: 8

Views: 15234

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86600

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.

Upvotes: 11

Related Questions