Feature extraction helps us get important information from data so the computer can learn better and faster.
Feature extraction approach in TensorFlow
base_model = tf.keras.applications.MobileNetV2(input_shape=(224,224,3), include_top=False, weights='imagenet') base_model.trainable = False inputs = tf.keras.Input(shape=(224,224,3)) x = base_model(inputs, training=False) x = tf.keras.layers.GlobalAveragePooling2D()(x) outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x) model = tf.keras.Model(inputs, outputs)
Set include_top=False to remove the final classification layer and get features.
Freeze the base model weights by setting trainable = False to avoid changing pre-trained features.
base_model = tf.keras.applications.ResNet50(include_top=False, weights='imagenet') base_model.trainable = False
x = base_model(inputs, training=False) x = tf.keras.layers.Flatten()(x) outputs = tf.keras.layers.Dense(10, activation='softmax')(x)
This example shows how to use MobileNetV2 as a feature extractor. We freeze its weights, add new layers, train on dummy data, and make predictions.
import tensorflow as tf # Load pre-trained MobileNetV2 without top layer base_model = tf.keras.applications.MobileNetV2(input_shape=(224,224,3), include_top=False, weights='imagenet') base_model.trainable = False # Build new model using feature extraction inputs = tf.keras.Input(shape=(224,224,3)) x = base_model(inputs, training=False) x = tf.keras.layers.GlobalAveragePooling2D()(x) outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x) model = tf.keras.Model(inputs, outputs) # Compile model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Create dummy data (10 images, 224x224 RGB) and labels import numpy as np data = np.random.random((10,224,224,3)).astype('float32') labels = np.random.randint(0,2,size=(10,1)) # Train model for 2 epochs history = model.fit(data, labels, epochs=2, verbose=2) # Predict on new dummy data predictions = model.predict(data[:2]) print('Predictions:', predictions.flatten())
Feature extraction saves time by reusing learned knowledge from big datasets.
Always preprocess input images the same way the pre-trained model expects.
Freezing the base model prevents losing the useful features it learned.
Feature extraction uses pre-trained models to get useful data features.
It helps when you have little data or want faster training.
Freeze the base model and add your own layers for your task.
Practice
Solution
Step 1: Understand feature extraction concept
Feature extraction uses a pre-trained model to get useful features learned from a large dataset.Step 2: Identify the benefit for new tasks
This helps when you have little data or want faster training by reusing learned features.Final Answer:
To use learned features from a large dataset to help a new task -> Option AQuick Check:
Feature extraction = reuse learned features [OK]
- Thinking feature extraction trains from scratch
- Confusing feature extraction with data augmentation
- Believing it reduces model layers automatically
Solution
Step 1: Recall how to freeze layers in TensorFlow
Settingtrainable = Falseon the base model freezes its weights.Step 2: Check each option's correctness
base_model.trainable = False correctly setsbase_model.trainable = False. Others are invalid syntax or do not freeze layers.Final Answer:
base_model.trainable = False -> Option BQuick Check:
Freeze layers = trainable False [OK]
- Using trainable = True to freeze layers
- Calling non-existent freeze() method
- Trying to set freeze attribute on layers directly
features?
base_model = tf.keras.applications.MobileNetV2(input_shape=(128,128,3), include_top=False) base_model.trainable = False inputs = tf.keras.Input(shape=(128,128,3)) features = base_model(inputs) print(features.shape)
Solution
Step 1: Understand MobileNetV2 output with include_top=False
MobileNetV2 outputs feature maps of size (4,4,1280) for 128x128 input when top layers are excluded.Step 2: Confirm batch dimension is None
The batch size is None (unspecified), so output shape is (None, 4, 4, 1280).Final Answer:
(None, 4, 4, 1280) -> Option AQuick Check:
MobileNetV2 feature shape = (None,4,4,1280) [OK]
- Confusing output with classification layer shape
- Assuming output shape equals input shape
- Ignoring batch dimension None
base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False) base_model.trainable = False inputs = tf.keras.Input(shape=(224,224,3)) x = base_model(inputs) x = tf.keras.layers.Dense(10)(x) model = tf.keras.Model(inputs, x)
Solution
Step 1: Check tensor shapes before Dense layer
Base model outputs 4D tensor (batch, height, width, channels). Dense expects 2D input.Step 2: Identify missing flatten or global pooling
Applying Dense directly to 4D tensor causes error; flatten or global pooling needed first.Final Answer:
Dense layer applied to 4D tensor without flattening -> Option CQuick Check:
Dense needs 2D input, flatten first [OK]
- Applying Dense directly to 4D output
- Confusing input shape requirements
- Misunderstanding trainable flag usage
Solution
Step 1: Understand why Dense layer causes error
MobileNetV2 outputs 4D feature maps; Dense layers need 2D input.Step 2: Use GlobalAveragePooling2D to convert 4D to 2D
Adding GlobalAveragePooling2D flattens spatial dimensions, making output suitable for Dense.Step 3: Evaluate other options
Changing input size is not required; training base model is optional; removing Dense loses classification ability.Final Answer:
Add a GlobalAveragePooling2D layer before the Dense layer -> Option DQuick Check:
Pool features before Dense layer [OK]
- Changing input size unnecessarily
- Trying to train frozen base model
- Skipping pooling and causing shape errors
Ready to prove it?
Pass the test and this pattern moves unknown
