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 validation_data when creating a Keras model in Python?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How do I check which version of Keras I am using in Python?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
- How do I use keras.utils.to_categorical in Python?
- How can I use Python Keras to develop a reinforcement learning model?
- How do I use Python Keras to zip a file?
- What is Python Keras and how is it used?
- How do I create a simple example using Python and Keras?
- How can I use Python Keras online?
See more codes...