Transfer learning helps you use a model trained on a big dataset to solve a new problem with a small dataset. It saves time and improves accuracy.
Transfer learning for small datasets in TensorFlow
base_model = tf.keras.applications.MobileNetV2(input_shape=(224,224,3), include_top=False, weights='imagenet') base_model.trainable = False model = tf.keras.Sequential([ base_model, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
Set include_top=False to remove the original classification layer.
Freeze the base model weights by setting trainable = False to avoid changing them during training.
base_model = tf.keras.applications.ResNet50(include_top=False, weights='imagenet') base_model.trainable = False
model = tf.keras.Sequential([
base_model,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(10, activation='softmax')
])This example shows how to use MobileNetV2 pretrained on ImageNet as a base model. We freeze it and add a new output layer for binary classification. We train on a tiny dataset of 10 random images and print predictions.
import tensorflow as tf from tensorflow.keras import layers # Load base model with pretrained weights, exclude top layer base_model = tf.keras.applications.MobileNetV2(input_shape=(224,224,3), include_top=False, weights='imagenet') base_model.trainable = False # Freeze base model # Build new model on top model = tf.keras.Sequential([ base_model, layers.GlobalAveragePooling2D(), layers.Dense(1, activation='sigmoid') ]) # Compile model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Create dummy small dataset (10 images, binary labels) x_train = tf.random.uniform((10,224,224,3)) y_train = tf.constant([0,1,0,1,0,1,0,1,0,1], dtype=tf.float32) # Train model on small dataset history = model.fit(x_train, y_train, epochs=3, verbose=2) # Make predictions predictions = model.predict(x_train) print('Predictions:', predictions.flatten())
Freezing the base model prevents losing the knowledge it already learned.
You can later unfreeze some layers to fine-tune the model if you get more data.
Use data augmentation to help small datasets generalize better.
Transfer learning uses a pretrained model to help with small datasets.
Freeze the base model layers to keep learned features.
Add new layers on top for your specific task and train only them.
Practice
Solution
Step 1: Understand transfer learning purpose
Transfer learning uses a pretrained model to leverage learned features from large datasets.Step 2: Relate to small dataset challenges
Small datasets lack enough data to train deep models well, so using pretrained knowledge helps.Final Answer:
To use a pretrained model's knowledge and avoid training from scratch -> Option BQuick Check:
Transfer learning = pretrained knowledge reuse [OK]
- Thinking transfer learning increases dataset size
- Believing all layers must be retrained
- Assuming transfer learning reduces model layers
Solution
Step 1: Recall how to freeze layers in TensorFlow
Settingtrainable = Falseon the base model freezes all its layers.Step 2: Check code options
Onlybase_model.trainable = Falseis valid TensorFlow syntax to freeze layers.Final Answer:
base_model.trainable = False-> Option CQuick Check:
Freeze layers = trainable False [OK]
- Using trainable = True instead of False
- Calling non-existent freeze_layers() method
- Trying to freeze layers with base_model.layers.freeze()
import tensorflow as tf base_model = tf.keras.applications.MobileNetV2(input_shape=(128,128,3), include_top=False, pooling='avg') base_model.trainable = False model = tf.keras.Sequential([ base_model, tf.keras.layers.Dense(10, activation='softmax') ]) model.build((None, 128, 128, 3)) predictions = model(tf.random.uniform((5, 128, 128, 3))) print(predictions.shape)
Solution
Step 1: Analyze model architecture
MobileNetV2 outputs pooled features (shape: (None, 1280)) due to pooling='avg'. Then Dense(10) outputs 10 classes.Step 2: Check input batch size and output shape
Input batch size is 5, so output shape is (5, 10) from Dense layer.Final Answer:
(5, 10) -> Option DQuick Check:
Batch 5, 10 classes output shape = (5, 10) [OK]
- Confusing input shape with output shape
- Expecting output shape to match input image shape
- Assuming output has 1000 classes from original MobileNet
base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False) base_model.trainable = False model = tf.keras.Sequential([ base_model, tf.keras.layers.Dense(5, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') model.fit(train_data, epochs=3)
What is the likely cause of the error?
Solution
Step 1: Check base_model input shape requirement
ResNet50 requires input_shape when include_top=False to build properly.Step 2: Identify error cause
Without input_shape, model layers don't connect correctly, causing training errors.Final Answer:
Missing input shape in base_model causing shape mismatch -> Option AQuick Check:
Input shape needed for base_model [OK]
- Not specifying input_shape for pretrained base model
- Thinking trainable must be True to avoid errors
- Changing loss function unnecessarily
Solution
Step 1: Consider dataset size and training time
Small dataset (200 images) benefits from freezing pretrained base to avoid overfitting and long training.Step 2: Choose transfer learning strategy
Freezing base layers and training new Dense layers adapts model to new task efficiently.Final Answer:
Use a pretrained model, freeze base layers, add new Dense layers, train only new layers -> Option AQuick Check:
Freeze base + train new layers = best for small data [OK]
- Training all layers on small data causing overfitting
- Training from scratch wasting time and data
- Not adding new layers for the specific task
Ready to prove it?
Pass the test and this pattern moves unknown
