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 theFlatten
function from thekeras.layers
library. -
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_tensor
variable. -
print(flatten_tensor)
: This line prints the output of theFlatten()
function.
Helpful links
More of Python Keras
- How do I use zero padding in Python Keras?
- How do I use Python Keras to create a Zoom application?
- How do I use Python Keras to zip a file?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I improve the validation accuracy of my Keras model using Python?
- How do I use validation_data when creating a Keras model in Python?
- How can I use Python and Keras to create a backend for my application?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How do I plot a model using Python and Keras?
- How can I install the python module tensorflow.keras in R?
See more codes...