• Transfer Learning: How to Reuse Pretrained Models, With a Keras Experiment

    transfer learning

    Transfer learning means reusing a model trained on one task as the starting point for another. Instead of training a neural network from random weights, you take one that has already learned from millions of examples, for instance an image model trained on ImageNet or a language model trained on a large part of the web, and adapt it to your problem with a fraction of the data and computing power. It is how most deep learning is done in practice today: almost every image classifier, chatbot and speech model built in 2026 starts from a pretrained model.

    This guide explains what transfer learning is, why it works, the difference between feature extraction and fine-tuning, how to choose a strategy for your data, and how transfer learning works for language models. In a hands-on Keras experiment we classify 3,670 flower photos three ways: with a network trained from scratch, with a frozen pretrained MobileNet and with fine-tuning, and we measure how many labelled photos transfer learning really needs.

    Key takeaways

    • Transfer learning reuses the knowledge a model gained on a large source task, such as recognising 1,000 ImageNet categories, for a new target task with less data.
    • It works because early layers learn general features (edges, textures, word meanings) that are useful for many tasks; only the last layers are task-specific.
    • Two main strategies: feature extraction (freeze the pretrained network and train a new output layer) and fine-tuning (also update some or all pretrained layers with a small learning rate).
    • In our experiment on 3,670 flower photos, a frozen MobileNet pretrained on ImageNet reached 88.4% accuracy against 74.4% for a network trained from scratch, while training only 5,125 weights instead of 390,000. With 20 photos per class it already matched the from-scratch model trained on all the data.
    • In language AI, transfer learning is the whole recipe: large models are pretrained once and then fine-tuned, often with parameter-efficient methods such as LoRA.

    What is transfer learning?

    Transfer learning is a machine learning technique in which knowledge gained while solving one problem, the source task, is applied to a different but related problem, the target task. A model trained to recognise 1,000 kinds of objects in photos already knows a lot about shapes, textures and parts of objects; that knowledge helps when you need to recognise flower species, defects on a production line or tumours in medical scans.

    The idea is old, but deep learning made it central. Training a large convolutional network from scratch needs hundreds of thousands or millions of labelled images and days on many GPUs. Most real projects have a few hundred or a few thousand images. Training a network with millions of weights on so little data leads to overfitting: the model memorises the training examples and fails on new ones. Starting from a pretrained network avoids this, because the network does not have to learn everything from zero.

    In practice this means three steps:

    1. Take a model pretrained on a large data set, usually from a library such as Keras Applications, torchvision or the Hugging Face Hub.
    2. Replace its output layer with a new one for your classes.
    3. Train the new layer, and optionally some of the pretrained layers, on your data.

    Why transfer learning works

    Deep neural networks learn a hierarchy of features. In an image model, the first layers detect simple patterns such as edges, colours and blobs; middle layers combine them into textures and object parts; the last layers respond to whole objects of the classes the network was trained on. A 2014 study by Jason Yosinski and colleagues measured this directly: features in the first layers were almost equally useful for very different tasks, while features in the top layers were specific to the original task.

    Inception-v3 architecture diagram from Google Research: stacks of convolution, pooling and inception modules ending in a softmax classifier
    Inception-v3, a classic ImageNet model: early blocks learn general features, the last layers are specific to the 1,000 ImageNet classes

    General features transfer; specific ones do not. That is why the usual recipe keeps the lower part of the network, the backbone, and replaces or retrains the top, the head. The same holds for language: the lower layers of a language model capture grammar and word meaning, which are useful for almost any text task.

    Feature extraction vs fine-tuning

    Feature extraction

    The pretrained network is frozen: its weights do not change. Each image is passed through the backbone once, and the output of the last pooling layer, a vector of several hundred or thousand numbers, serves as a description of the image. A small classifier, often a single dense layer or even logistic regression, is trained on these vectors. This is fast, needs little data and works on a CPU, because the expensive network runs only once per image.

    Fine-tuning

    Fine-tuning goes further: after the new head has been trained, some or all of the pretrained layers are unfrozen and trained together with it, with a learning rate 10 to 100 times smaller than usual, so that the useful pretrained features are adjusted rather than destroyed. Fine-tuning usually gives higher accuracy, especially when the new images look different from the original training data, but it costs more computation and needs more care to avoid overfitting.

    Feature extraction Fine-tuning
    What is trained Only the new head The head and the top (or all) pretrained layers
    Data needed Very little: tens of examples per class can work More: hundreds or more per class
    Compute One pass through the backbone Many passes with backpropagation through the unfrozen layers
    Accuracy Good when the data is similar to the source Usually higher, especially for different domains
    Risk Low Overfitting and forgetting if the learning rate is too high

    A common workflow combines both: first train the head on frozen features, then unfreeze the top blocks and fine-tune with a small learning rate. Training a randomly initialised head and unfrozen layers at the same time is risky, because the large gradients from the random head can damage the pretrained weights in the first steps.

    Which strategy to use: four scenarios

    The right choice depends on two questions: how much data you have, and how similar it is to the data the model was pretrained on.

    Inception-v3 network diagram showing where a pretrained network can be cut and a new classifier attached
    Where to cut: the lower part of a pretrained network is kept, the top is replaced or retrained
    1. Small data set, similar to the source data (for example, a few hundred photos of everyday objects with an ImageNet model): use feature extraction. Fine-tuning a large network on little data risks overfitting, and the top-level features are already relevant.
    2. Large data set, similar to the source: fine-tune the whole network or most of it. There is enough data to adjust all layers without overfitting.
    3. Small data set, different from the source (for example, X-ray or satellite images): use features from earlier layers, which are more general, or fine-tune only the top blocks carefully, with strong data augmentation.
    4. Large data set, different from the source: fine-tune the whole network. Training from scratch is also possible, but starting from pretrained weights usually still converges faster and reaches a better result.

    Pretrained models to start from

    • Image classification backbones: ResNet, EfficientNet, MobileNet (small and fast, designed for phones), ConvNeXt and vision transformers (ViT), all available pretrained on ImageNet in Keras Applications, torchvision and timm. Older classics such as VGG16 and Inception-v3 still appear in tutorials.
    • General visual features: self-supervised models such as Meta’s DINOv2 and image-text models such as OpenAI’s CLIP and Google’s SigLIP give strong features for many tasks without any fine-tuning.
    • Object detection and segmentation: detectors such as the YOLO family and segmentation models such as Meta’s Segment Anything come pretrained on large labelled data sets and are fine-tuned for specific objects.
    • Language: BERT-style encoders for classification and search, and open large language models such as Llama, Qwen, Gemma and Mistral for generation.
    • Speech and audio: Whisper for speech recognition, wav2vec 2.0 and similar models for audio features.

    The Hugging Face Hub alone hosts well over a million pretrained models, so for most tasks the question is not whether a starting point exists, but which one fits your data, latency and licence requirements.

    Experiment: transfer learning in Keras

    We tested transfer learning on the flower photos data set from the TensorFlow tutorials: 3,670 photos of daisies, dandelions, roses, sunflowers and tulips taken by Flickr users (CC BY 2.0 licence). This is the same data set the original TensorFlow “retrain Inception-v3” tutorial used. We held out 734 photos (20%) for testing and compared three approaches on a CPU with two cores:

    1. From scratch: a small convolutional network with four convolution blocks and 390,000 weights, initialised randomly and trained for 15 epochs with random horizontal flips as data augmentation.
    2. Feature extraction: MobileNet, a compact network from Google pretrained on the 1.28 million images of ImageNet, frozen and used to turn every photo into 1,024 numbers; a single new dense layer is trained on top. We also repeated this with only 5, 20, 100 and 400 photos per class.
    3. Fine-tuning: the trained classifier plus the top of MobileNet (its last 23 layers, 2.1 million weights), trained together for 5 epochs with a learning rate of 0.00001.

    The code uses Keras 3, which runs on top of PyTorch, JAX or TensorFlow; we used the PyTorch backend. Put the five class folders from flower_photos.tgz in a data folder. The pretrained MobileNet weights file mobilenet_1_0_224_tf_no_top.h5 normally downloads automatically with weights="imagenet"; we loaded a local copy from the Keras deep-learning-models releases on GitHub into a dl folder.

    import os
    os.environ["KERAS_BACKEND"] = "torch"   # Keras 3 runs on PyTorch, JAX or TensorFlow
    import time
    
    import numpy as np
    import keras
    from keras import layers
    from PIL import Image
    
    # 1. Data: 3,670 flower photos in 5 classes (TensorFlow flower_photos, CC BY 2.0)
    classes = ["daisy", "dandelion", "roses", "sunflowers", "tulips"]
    images, labels = [], []
    for label, name in enumerate(classes):
        for file in sorted(os.listdir(f"data/{name}")):
            img = Image.open(f"data/{name}/{file}").convert("RGB").resize((160, 160))
            images.append(np.asarray(img))
            labels.append(label)
    x, y = np.stack(images), np.array(labels)
    rng = np.random.default_rng(0)
    order = rng.permutation(len(x))
    test, train = order[:734], order[734:]                  # 20% of the photos are held out for testing
    print(f"{len(train)} training and {len(test)} test images")
    
    augment = layers.RandomFlip("horizontal")                 # data augmentation: random mirror images
    
    # 2. Baseline: a small convolutional network trained from scratch
    keras.utils.set_random_seed(0)
    scratch = keras.Sequential([keras.Input((160, 160, 3)), augment, layers.Rescaling(1 / 255)] +
                               [layer for f in [32, 64, 128, 256] for layer in
                                (layers.Conv2D(f, 3, padding="same", activation="relu"), layers.MaxPooling2D())] +
                               [layers.GlobalAveragePooling2D(), layers.Dropout(0.3), layers.Dense(5, activation="softmax")])
    scratch.compile(optimizer=keras.optimizers.Adam(1e-3), loss="sparse_categorical_crossentropy", metrics=["accuracy"])
    start = time.time()
    scratch.fit(x[train], y[train], epochs=15, batch_size=32, verbose=0)
    acc = scratch.evaluate(x[test], y[test], verbose=0)[1]
    print(f"From scratch (small CNN, 15 epochs):        test accuracy {acc:.3f}  {time.time() - start:5.0f} s  "
          f"{scratch.count_params():,} weights trained")
    
    # 3. Transfer learning, step 1: MobileNet pretrained on ImageNet as a frozen feature extractor
    base = keras.applications.MobileNet(input_shape=(160, 160, 3), include_top=False, pooling="avg",
                                        weights="dl/mobilenet_1_0_224_tf_no_top.h5")
    base.trainable = False
    start = time.time()
    features = base.predict(keras.applications.mobilenet.preprocess_input(x.astype("float32")), batch_size=64, verbose=0)
    print(f"Feature extraction: {features.shape[1]} numbers per photo, {time.time() - start:.0f} s for all photos")
    
    def train_head(idx, epochs=30):
        keras.utils.set_random_seed(0)
        head = keras.Sequential([keras.Input((features.shape[1],)), layers.Dropout(0.2), layers.Dense(5, activation="softmax")])
        head.compile(optimizer=keras.optimizers.Adam(1e-3), loss="sparse_categorical_crossentropy", metrics=["accuracy"])
        head.fit(features[idx], y[idx], epochs=epochs, batch_size=32, verbose=0)
        return head, head.evaluate(features[test], y[test], verbose=0)[1]
    
    head, acc = train_head(train)
    print(f"Transfer: frozen MobileNet + new classifier: test accuracy {acc:.3f}  {head.count_params():,} weights trained")
    
    # 4. How many examples does transfer learning need? Train the classifier on 5 to 400 photos per class
    for per_class in [5, 20, 100, 400]:
        idx = np.concatenate([train[y[train] == c][:per_class] for c in range(5)])
        print(f"  {per_class:3d} photos per class ({len(idx):4d} in total): test accuracy {train_head(idx)[1]:.3f}")
    
    # 5. Transfer learning, step 2: fine-tuning, unfreeze the top of MobileNet and train with a small learning rate
    keras.utils.set_random_seed(0)
    inputs = keras.Input((160, 160, 3))
    h = layers.Rescaling(1 / 127.5, offset=-1)(augment(inputs))   # the same scaling MobileNet was trained with
    model = keras.Model(inputs, head(base(h, training=False)))
    base.trainable = True
    for layer in base.layers[:-23]:                                  # train only the last 23 layers of MobileNet
        layer.trainable = False
    model.compile(optimizer=keras.optimizers.Adam(1e-5), loss="sparse_categorical_crossentropy", metrics=["accuracy"])
    start = time.time()
    model.fit(x[train], y[train], epochs=5, batch_size=32, verbose=0)
    acc = model.evaluate(x[test], y[test], verbose=0)[1]
    trainable = sum(np.prod(w.shape) for w in model.trainable_weights)
    print(f"Transfer + fine-tuning (5 epochs):          test accuracy {acc:.3f}  {time.time() - start:5.0f} s  "
          f"{trainable:,} weights trained")
    2936 training and 734 test images
    From scratch (small CNN, 15 epochs):        test accuracy 0.744   1773 s  389,701 weights trained
    Feature extraction: 1024 numbers per photo, 81 s for all photos
    Transfer: frozen MobileNet + new classifier: test accuracy 0.884  5,125 weights trained
        5 photos per class (  25 in total): test accuracy 0.571
       20 photos per class ( 100 in total): test accuracy 0.737
      100 photos per class ( 500 in total): test accuracy 0.832
      400 photos per class (2000 in total): test accuracy 0.869
    Transfer + fine-tuning (5 epochs):          test accuracy 0.872    342 s  2,130,949 weights trained
    Test accuracy on flower photos: network trained from scratch 74.4%, frozen pretrained MobileNet 88.4%, fine-tuned MobileNet 87.2%, and frozen MobileNet accuracy with 5 to 400 training photos per class
    A frozen pretrained network beats training from scratch, and needs only about 20 photos per class to match it

    What the experiment shows:

    • Transfer learning wins by a wide margin. The frozen MobileNet with a new classifier reached 88.4% test accuracy; the network trained from scratch reached 74.4%. The pretrained model makes 55% fewer mistakes (11.6% error against 25.6%).
    • It needs a fraction of the data. With only 20 photos per class, 100 in total, transfer learning reached 73.7%, the same level as the from-scratch network trained on all 2,936 photos. With 100 photos per class it reached 83.2%. Even 5 photos per class gave 57%, against 20% for random guessing.
    • And a fraction of the computation. Training from scratch took 30 minutes on the CPU. Feature extraction needed one pass of MobileNet over all photos, 81 seconds, after which the classifier with 5,125 weights trained in seconds.
    • Fine-tuning did not help here. Unfreezing the top of MobileNet gave 87.2%, within the noise of the frozen model’s 88.4% (on 734 test photos, one percentage point is about seven photos). Flowers are everyday objects similar to ImageNet, and 2,936 photos is a small data set, which is exactly the first scenario above: feature extraction is enough. Fine-tuning pays off with more data, more epochs and data that looks less like ImageNet.

    The from-scratch number could be improved with a deeper network, stronger augmentation and many more epochs, but closing the gap would cost hours of computation that transfer learning saves. That is the practical argument for transfer learning: better results with less data and less compute.

    Transfer learning in NLP and large language models

    In natural language processing, transfer learning took over after 2018. Earlier, word vectors such as word2vec transferred only the meaning of individual words. Then ULMFiT, ELMo and especially BERT (Google, 2018) showed that a whole network pretrained on large amounts of text could be fine-tuned for classification, question answering or named entity recognition with little labelled data, beating models trained from scratch by large margins.

    Today’s large language models follow the same two-stage recipe at a much larger scale:

    1. Pretraining on trillions of words to predict the next token, which teaches grammar, facts and reasoning patterns. This is the expensive step, done once.
    2. Adaptation to a task or behaviour: instruction tuning, reinforcement learning from human feedback, or fine-tuning on a company’s own documents.

    Fine-tuning all the weights of a model with billions of parameters is expensive, so parameter-efficient fine-tuning (PEFT) has become standard. LoRA (Low-Rank Adaptation, Microsoft, 2021) freezes the pretrained weights and trains small low-rank matrices added to some layers, often well under 1% of the model’s parameters; QLoRA adds 4-bit quantisation so that models with tens of billions of parameters can be fine-tuned on a single GPU. Many tasks need no training at all: with in-context learning, a few examples in the prompt are enough, and retrieval-augmented generation supplies the model with relevant documents instead of baking them into the weights.

    Pitfalls and limitations

    • Wrong preprocessing. A pretrained model expects inputs prepared exactly as during its training: the same image size range, colour order and pixel scaling. MobileNet expects pixels scaled to the range −1 to 1; ResNet in Keras expects mean-subtracted BGR. A mismatch silently ruins accuracy.
    • Too high a learning rate when fine-tuning. Large updates destroy the pretrained features, an effect called catastrophic forgetting. Use a learning rate 10 to 100 times smaller than for training from scratch.
    • Batch normalisation layers. When fine-tuning with small batches, keep batch normalisation layers in inference mode (in Keras, call the base model with training=False) so that their statistics from pretraining are not overwritten.
    • Negative transfer. If the source and target domains are too different, pretrained features can help little or even hurt. Compare against a simple baseline.
    • Inherited bias and licences. A pretrained model brings the biases of its training data and comes with a licence that may restrict commercial use. Check both before deploying.

    FAQ

    What is transfer learning in simple terms?

    It is reusing what a model has already learned. A network trained on millions of images already knows how to see edges, textures and shapes, so you only need to teach it your specific classes, which takes far fewer examples and much less time than starting from scratch.

    What is the difference between transfer learning and fine-tuning?

    Transfer learning is the general idea of reusing a pretrained model. Fine-tuning is one way to do it: continuing to train some or all of the pretrained layers on new data. The other main way is feature extraction, where the pretrained layers stay frozen and only a new output layer is trained.

    When should I use transfer learning?

    Almost always when you have limited labelled data and a pretrained model exists for a related domain, which is true for most image, text and audio tasks. Training from scratch makes sense mainly when you have a very large data set from a domain unlike anything public models were trained on.

    How much data do I need for transfer learning?

    Far less than for training from scratch. In our experiment, a frozen pretrained network with a new classifier reached 74% accuracy with only 20 photos per class. Fine-tuning benefits from more data: hundreds of examples per class are a comfortable start.

    Is transfer learning supervised or unsupervised?

    It can be both. The pretraining step is often self-supervised, as with language models that predict the next word, or supervised, as with ImageNet classification. The adaptation step is usually supervised, using labelled examples of the target task.

    Which pretrained model should I choose?

    Start with a model pretrained on data similar to yours, then balance accuracy against size and speed. For images on a laptop or phone, MobileNet and EfficientNet are good first choices; for the best accuracy, larger ConvNeXt or vision transformer models. For text, choose a BERT-style encoder for classification and search, and an open LLM with LoRA for generation tasks.


    bnr2mob
    Subscribe
    Notify of
    guest

    0 Comments
    Oldest
    Newest Most Voted