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 Python and Keras to create a tutorial?
- How do I use zero padding in Python Keras?
- How to load a model in Python Keras?
- How do Python Keras and TensorFlow compare in developing machine learning models?
- How do I uninstall Keras from my Python environment?
- How do I use keras.utils.to_categorical in Python?
- How do I use the to_categorical function in Python Keras?
- How can I use the Adam optimizer in TensorFlow?
- How do I use Python Keras to create a regression example?
- How can I use Python Keras to create a neural network with zero hidden layers?
See more codes...