Providing TensorFlow transfer learning code
Here’s a complete Python example using TensorFlow to implement image classification with MobileNetV2 transfer learning, freezing the base layers and training only the top custom dense layer:
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
# Parameters
image_size = (224, 224)
batch_size = 32
num_classes = 5 # adjust to your number of classes
# Load datasets from directories (replace 'train_dir' and 'val_dir' with your paths)
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
'train_dir',
image_size=image_size,
batch_size=batch_size,
label_mode='int'
)
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
'val_dir',
image_size=image_size,
batch_size=batch_size,
label_mode='int'
)
# Apply MobileNetV2 preprocessing
train_ds = train_ds.map(lambda x, y: (preprocess_input(x), y))
val_ds = val_ds.map(lambda x, y: (preprocess_input(x), y))
# Load MobileNetV2 without the top layer
base_model = MobileNetV2(
input_shape=image_size + (3,),
include_top=False,
weights='imagenet'
)
base_model.trainable = False # freeze base layers
# Build the model
inputs = layers.Input(shape=image_size + (3,))
x = base_model(inputs, training=False)
x = layers.GlobalAveragePooling2D()(x)
outputs = layers.Dense(num_classes, activation='softmax')(x)
model = models.Model(inputs, outputs)
# Compile the model
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Train only the top layer
model.fit(
train_ds,
validation_data=val_ds,
epochs=5
)
```</think>
Below is an example that shows how to use transfer learning with MobileNetV2 in TensorFlow. It loads the base model without the top classification layer, freezes its weights, then adds a custom classification head and trains only that head. You can adapt paths, image sizes, batch sizes, and number of classes as needed.
```python
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
# -------------------------------------------------------------------
# 1. Load and prepare your dataset
# Replace "path_to_train" and "path_to_val" with your directory paths.
# Your dataset folders should have one subfolder per class.
# -------------------------------------------------------------------
batch_size = 32
img_size = (224, 224)
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
"path_to_train",
validation_split=0.2, # optional if you want a split from the same directory
subset="training",
seed=123,
image_size=img_size,
batch_size=batch_size
)
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
"path_to_train",
validation_split=0.2,
subset="validation",
seed=123,
image_size=img_size,
batch_size=batch_size
)
num_classes = train_ds.cardinality().numpy() # or set manually if known
class_names = train_ds.class_names # handy for checking class names
# Optional: improve I/O performance
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.map(lambda x, y: (preprocess_input(x), y))
val_ds = val_ds.map(lambda x, y: (preprocess_input(x), y))
train_ds = train_ds.prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.prefetch(buffer_size=AUTOTUNE)
# -------------------------------------------------------------------
# 2. Load pre-trained MobileNetV2 without the top layer
# -------------------------------------------------------------------
base_model = MobileNetV2(
input_shape=img_size + (3,),
include_top=False,
weights="imagenet"
)
# Freeze the base model
base_model.trainable = False
# -------------------------------------------------------------------
# 3. Add custom classification head
# -------------------------------------------------------------------
inputs = tf.keras.Input(shape=img_size + (3,))
x = base_model(inputs, training=False) # Set training=False for the base model
x = layers.GlobalAveragePooling2D()(x)
outputs = layers.Dense(num_classes, activation="softmax")(x)
model = models.Model(inputs, outputs)
# -------------------------------------------------------------------
# 4. Compile and train
# -------------------------------------------------------------------
model.compile(
optimizer=tf.keras.optimizers.Adam(),
loss="sparse_categorical_crossentropy", # use "categorical_crossentropy" if labels are one-hot
metrics=["accuracy"]
)
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=5 # increase as needed
)
# -------------------------------------------------------------------
# 5. (Optional) Fine-tuning
# Once the top layers are trained, you can unfreeze some of the base_model
# layers to fine-tune at a low learning rate:
# -------------------------------------------------------------------
base_model.trainable = True
# Set a small learning rate for fine-tuning
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-5),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
# Fine-tune a few more epochs if desired
# history_fine = model.fit(train_ds, validation_data=val_ds, epochs=5)
Key points to note:
include_top=False ensures the MobileNetV2 base model does not include its original classifier layer.
base_model.trainable = False freezes the convolutional layers so that only your newly added dense layer is trained initially.
- You can later unfreeze parts of the base model to fine-tune at a low learning rate if you need higher accuracy.