📜  keras reshape - Python (1)

📅  最后修改于: 2023-12-03 15:17:08.145000             🧑  作者: Mango

Keras Reshape - Python

Keras is an open source deep learning framework written in Python, used for building neural networks. It provides high-level building blocks for developing deep learning models, with built-in support for popular deep learning libraries such as TensorFlow, Theano and CNTK.

One of the important layers in Keras is the Reshape layer, which is used to reshape the input tensor. The Keras Reshape layer takes an input tensor of shape (batch_size, input_dim) and returns an output tensor of shape (batch_size, output_dim).

Reshape Layer in Keras

The syntax for adding a Reshape layer in Keras is as follows:

from keras.layers import Reshape

model.add(Reshape((output_dim,), input_shape=(input_dim,)))

The Reshape layer takes two arguments:

  • output_dim: The desired output dimension of the layer.
  • input_shape: The shape of the input tensor.

Here's an example of adding a Reshape layer in a Keras model:

from keras.models import Sequential
from keras.layers import Reshape, Dense

model = Sequential()
model.add(Reshape((4,), input_shape=(2,)))
model.add(Dense(2))

In the above example, we have added a Reshape layer that takes an input tensor of shape (batch_size, 2) and returns an output tensor of shape (batch_size, 4).

Reshaping Tensors in Keras

In Keras, we can also reshape tensors using the K.reshape method. Here's an example:

from keras import backend as K

x = K.ones((2, 4))
y = K.reshape(x, (4, 2))

In the above example, we have created a tensor x with shape (2, 4) and then reshaped it to a tensor y with shape (4, 2) using the K.reshape method.

Conclusion

The Reshape layer in Keras is a powerful tool for reshaping tensors in deep learning models. It is used to modify the shape of the input or output tensors of a layer, and can be used to create more complex neural network architectures.