python-kerasHow do I use the Keras Flatten function in Python?
The Flatten function in Keras is used to flatten a multi-dimensional tensor into a one-dimensional tensor. It can be used to convert a 2D or 3D tensor into a single vector.
Example code
from keras.layers import Flatten
# Create a 3D tensor
input = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]
# Flatten the input tensor
flatten_tensor = Flatten()(input)
# Print the output
print(flatten_tensor)
Output example
tf.Tensor([ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18], shape=(18,), dtype=int32)
The code above first imports the Flatten function from the keras.layers library. Then it creates a 3D tensor and passes it as an argument to the Flatten() function. The output of the function is a single vector containing all the elements of the 3D tensor.
Code explanation
-
from keras.layers import Flatten: This line imports theFlattenfunction from thekeras.layerslibrary. -
input = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]: This line creates a 3D tensor. -
flatten_tensor = Flatten()(input): This line passes the 3D tensor as an argument to theFlatten()function and assigns the output to theflatten_tensorvariable. -
print(flatten_tensor): This line prints the output of theFlatten()function.
Helpful links
More of Python Keras
- How do I check which version of Keras I am using in Python?
- How do I use Python Keras to create a regression example?
- How do I use Python Keras to zip a file?
- How do I use zero padding in Python Keras?
- How can I use Python Keras to create a neural network with zero hidden layers?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How do I save weights in a Python Keras model?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I install the python module tensorflow.keras in R?
- How do I install Keras on Windows using Python?
See more codes...