Transfer Learning and Model Zoo Workflows
This page shows how to use existing deep neural networks: adapting ResNet50 to CIFAR-10, freezing a pretrained base model, loading models from TensorFlow Hub and PyTorch, and running YOLO pose tracking in Colab.
- Resize and preprocess images for a pretrained network.
- Attach a new classification head to a pretrained ResNet50 base.
- Freeze pretrained layers when using transfer learning as a feature extractor.
- Recognize model zoo workflows across TensorFlow Hub, PyTorch, and Ultralytics YOLO.
- Save Colab prediction outputs back to Google Drive.
- include_top=False removes the original ImageNet classifier so a new task-specific head can be added.
- The final Dense layer must match the number of target classes.
- Setting trainable=False freezes pretrained weights during training.
Transfer Learning with ResNet50
Listing 1. Import TensorFlow, ResNet50, preprocessing, and one-hot helpers
This transforms the raw input into the numeric scale or shape expected by the model.
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.utils import to_categoricalListing 2. Load, resize, preprocess, and one-hot encode CIFAR-10 data
This prepares the data or pretrained resource used by the following examples.
(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()
x_train = x_train[:2000]
y_train = y_train[:2000]
x_test = x_test[:100]
y_test = y_test[:100]
# required image resizing
x_train = tf.image.resize(x_train, (224, 224))
x_test = tf.image.resize(x_test, (224, 224))
# required preprocessing for ResNet50
x_train = preprocess_input(x_train)
x_test = preprocess_input(x_test)
# one-hot encoding
y_train = to_categorical(y_train, num_classes=10) # CIFAR-10 has 10 classes
y_test = to_categorical(y_test, num_classes=10)Expected text output or note
[download or training progress output omitted; run the cell to see live progress]Listing 3. Build a ResNet50 transfer-learning classifier
This step supports the workflow shown in the surrounding listings.
base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(224, 224, 3))
model = models.Sequential()
model.add(base_model)
model.add(layers.GlobalAveragePooling2D())
model.add(layers.Dense(1000, activation="relu"))
model.add(layers.Dense(10, activation="softmax")) # the neuron count must match the number of classesExpected text output or note
[download or training progress output omitted; run the cell to see live progress]Listing 4. Compile the ResNet50 classifier
Compilation chooses the loss function, optimizer, and metrics used during training.
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])Listing 5. Train the unfrozen transfer-learning model
Training updates model weights and stores the learning history for later inspection.
history=model.fit(x_train, y_train, epochs=10, validation_split=0.3)Expected text output or note
[download or training progress output omitted; run the cell to see live progress]Listing 6. Plot the unfrozen model training history
Training updates model weights and stores the learning history for later inspection.
import pandas as pd
import matplotlib.pyplot as plt
pd.DataFrame(history.history).plot(figsize=(8,5))
plt.grid(True)
plt.ylim(0, 1)
plt.xlabel('Epochs')
plt.showExpected text output or note
<function matplotlib.pyplot.show(close=None, block=None)>
<Figure size 800x500 with 1 Axes>
[visual output omitted; run the code to display the image or chart]Listing 7. Build a frozen ResNet50 feature extractor model
This defines or inspects part of the neural network architecture.
frozen_base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(224, 224, 3))
frozen_base_model.trainable = False # freeze pretrained weights
frozen_transfer_model = models.Sequential()
frozen_transfer_model.add(frozen_base_model)
frozen_transfer_model.add(layers.GlobalAveragePooling2D())
frozen_transfer_model.add(layers.Dense(1024, activation="relu"))
frozen_transfer_model.add(layers.Dense(10, activation="softmax"))Listing 8. Compile the frozen transfer-learning model
Compilation chooses the loss function, optimizer, and metrics used during training.
frozen_transfer_model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])Listing 9. Train the frozen transfer-learning model
Training updates model weights and stores the learning history for later inspection.
frozen_history=frozen_transfer_model.fit(x_train, y_train, epochs=10, validation_split=0.3)Expected text output or note
[download or training progress output omitted; run the cell to see live progress]Listing 10. Plot the frozen model training history
Training updates model weights and stores the learning history for later inspection.
import pandas as pd
import matplotlib.pyplot as plt
pd.DataFrame(frozen_history.history).plot(figsize=(8,5))
plt.grid(True)
plt.ylim(0, 1)
plt.xlabel('Epochs')
plt.showExpected text output or note
<function matplotlib.pyplot.show(close=None, block=None)>
<Figure size 800x500 with 1 Axes>
[visual output omitted; run the code to display the image or chart]Model Zoo Examples
Listing 11. Load an object-detection model from TensorFlow Hub
This prepares the data or pretrained resource used by the following examples.
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
import cv2
# load a pretrained model from TensorFlow Hub
model = hub.load("https://tfhub.dev/tensorflow/ssd_mobilenet_v2/2")Listing 12. Load a pretrained ResNet50 model from PyTorch
This prepares the data or pretrained resource used by the following examples.
import torch
import torchvision.transforms as transforms
from PIL import Image
from torchvision import models
# Load the pre-trained model
model = models.resnet50(pretrained=True)
model.eval()YOLO Pose Tracking in Colab
Listing 13. Install Ultralytics YOLO in Colab
This step supports the workflow shown in the surrounding listings.
%pip install ultralyticsListing 14. Run YOLO pose tracking on a video
This step supports the workflow shown in the surrounding listings.
from ultralytics import YOLO
# load an official model
pose_model = YOLO('yolov8l-pose.pt')
# Predict with the model
# pass the video path as input
results = pose_model.track('/content/clip_1.mp4', save=True, save_txt=True, imgsz=1920)Listing 15. Mount Google Drive for saving outputs
This step supports the workflow shown in the surrounding listings.
from google.colab import drive
drive.mount('/content/drive')Listing 16. Copy the tracked video to Drive
This step supports the workflow shown in the surrounding listings.
# save to Drive and adjust the path as needed
!cp runs/pose/track/clip_1.avi /content/drive/MyDrive/Materijali_IS1/clip_1_tracking.aviListing 17. Copy YOLO label files to Drive
This step supports the workflow shown in the surrounding listings.
!cp -r runs/pose/track/labels/ /content/drive/MyDrive/Materijali_IS1/clip_1_prediction_trackListing 18. Zip the YOLO label output folder
This step supports the workflow shown in the surrounding listings.
!zip -qr clip_1_prediction_track.zip /content/drive/MyDrive/Materijali_IS1/clip_1_prediction_track