Flatten and Dense layers help a neural network understand and learn from data by organizing it into simple shapes and making decisions.
Flatten and Dense layers in TensorFlow
from tensorflow.keras.layers import Flatten, Dense # Flatten layer example flatten_layer = Flatten(input_shape=(height, width, channels)) # Dense layer example dense_layer = Dense(units=number_of_neurons, activation='activation_function')
The Flatten layer changes multi-dimensional data into a flat list.
The Dense layer is a fully connected layer where each neuron connects to all inputs.
Flatten(input_shape=(28, 28, 1))
Dense(units=128, activation='relu')
Dense(units=10, activation='softmax')
This code builds a simple neural network with Flatten and Dense layers to classify 28x28 grayscale images into 10 classes. It trains on random data for 2 epochs and shows prediction results.
import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Flatten, Dense # Create a simple model model = Sequential([ Flatten(input_shape=(28, 28, 1)), # Flatten 2D input to 1D Dense(128, activation='relu'), # Hidden layer Dense(10, activation='softmax') # Output layer for 10 classes ]) # Compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Create dummy data: 100 samples of 28x28 grayscale images and labels import numpy as np x_train = np.random.random((100, 28, 28, 1)) y_train = np.random.randint(0, 10, 100) # Train the model for 2 epochs history = model.fit(x_train, y_train, epochs=2, verbose=2) # Make predictions on first 5 samples predictions = model.predict(x_train[:5]) print('Predictions shape:', predictions.shape) print('Predictions for first sample:', predictions[0])
The Flatten layer does not learn any parameters; it just reshapes data.
Dense layers learn weights and biases to find patterns in data.
Activation functions like ReLU and softmax help the model learn complex patterns and output probabilities.
Flatten turns multi-dimensional data into a flat list for Dense layers.
Dense layers connect all inputs to neurons to learn from data.
Together, they help build simple neural networks for classification tasks.