Intermediate Level:
1. Customizing Models with the Functional API:
- Explore the Functional API for more complex model architectures.
python code
inputs = tf.keras.Input(shape=(input_size,)) x = tf.keras.layers.Dense(64, activation='relu')(inputs) outputs = tf.keras.layers.Dense(10, activation='softmax')(x) model = tf.keras.Model(inputs=inputs, outputs=outputs)
Explanation:
- Creates an input layer with a specified shape of (input_size,). This defines the shape of the input data that the model will receive.
- Adds a dense layer with 64 units and a ReLU activation function.
- Connects this layer to the previously defined input layer (inputs).
- Adds an output layer with 10 units (assuming it’s a classification problem with 10 classes) and a softmax activation function.
- Connects this layer to the previously defined dense layer (x).
- Creates the model using the Model class from Keras.
- Specifies the input and output layers for the model.
2. Handling Data with TensorFlow Datasets:
- Learn to use TensorFlow Datasets for efficient data loading and preprocessing.
python code
import tensorflow_datasets as tfds
dataset = tfds.load(name="mnist", split=tfds.Split.TRAIN)
Explanation:
- Imports the TensorFlow Datasets library, commonly abbreviated as
tfds
. This library provides various datasets for machine learning. - Uses the
load
function from TFDS to load the MNIST dataset. name="mnist"
: Specifies that the dataset to be loaded is the MNIST dataset, which is a dataset of handwritten digits.split=tfds.Split.TRAIN
: Specifies that the training split of the MNIST dataset should be loaded. This split contains the training examples.
3. Transfer Learning with Pre-trained Models:
- Fine-tune a pre-trained model for a new task.
python code
base_model = tf.keras.applications.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights='imagenet')
model = tf.keras.Sequential([
base_model,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(10, activation='softmax')
])
Explanation:
- Imports the MobileNetV2 model from TensorFlow Keras Applications.
input_shape=(224, 224, 3)
: Specifies the input shape of the images expected by the model. In this case, it’s set to 224×224 pixels with 3 channels (RGB).include_top=False
: Indicates that the final dense layers (classification head) of the MobileNetV2 model should not be included. This is useful if you want to add your own classification layers.weights='imagenet'
: Initializes the model with pre-trained weights on the ImageNet dataset.- Creates a new sequential model.
- Adds the MobileNetV2 base model as the first layer (
base_model
) in the sequential model. - Adds a
GlobalAveragePooling2D
layer, which reduces the spatial dimensions of the feature map and computes the average value for each channel. This is a common technique before adding a dense layer for classification. - Adds a dense layer with 10 units (assuming it’s a classification problem with 10 classes) and a softmax activation function.