Zero Labs
Industry News / AI

Transfer Learning with MobileNetV2 in Keras: A Practical Guide

Source · Towards AI By Fahad Ur Rehman

From the publisher’s feed, collected in the ZeroLabs newsroom.

How I Built a Flower Classifier by Borrowing a Pretrained BrainA practical guide to transfer learning with TensorFlow, Keras and MobileNetV2, with full code, five pitfalls to avoid, and a checklist you can reuseKey takeaways:Transfer learning means reusing a network already trained on a huge dataset (ImageNet, about 1.28 million images) and adapting it to your own, smaller problem.I took MobileNetV2, removed its ImageNet classifier, froze the rest, and added a tiny head to classify 5 types of flowers from 3,670 photos.The new head has just 6,405 trainable parameters. The frozen base has about 2.26 million.The technique works, but five small mistakes can quietly ruin it. They’re covered below.3,670 photos and one big problemHere’s a number: 3,670.That’s how many flower photos I had to teach a neural network the difference between roses, daisies, dandelions, sunflowers and tulips.For deep learning, that’s tiny. The famous ImageNet dataset has about 1.28 million training images. Train a deep convolutional network from scratch on 3,670 photos and it will do what small datasets make networks do: memorize the training set and fall apart on new images.So I didn’t train from scratch. I used transfer learning.By the end of this article you’ll know how it works, how to build it in about 20 lines of Keras, and the mistakes that silently wreck most transfer learning projects.Don’t train a brain from scratch. Borrow one that has already learned how to see.What is transfer learning?Transfer learning is a machine learning technique where a model trained on one task is reused as the starting point for a different task.Think of a radiologist who has studied thousands of scans. If you asked them to start reading a new type of scan, they wouldn’t begin from zero. They already know what edges, shapes, textures and abnormalities look like. They only need to learn what’s specific to the new scan.Neural networks work the same way:Early layers → edges, corners, coloursMiddle layers → textures, patterns, simple shapesLater layers → task-specific parts (e.g. "dog ear", "car wheel")Final layer → the actual decision (1,000 ImageNet classes)The early and middle layers learn things that are useful for almost any image task. The final layer is the part that’s specific to the original task. So we keep the first part and replace the last.Pretrained base (frozen) ──► Global average pooling ──► New Dense(5) "how to see" "summarise" "which flower?"Two flavours: feature extraction vs fine-tuningPeople often mix these up, so here’s the difference:Feature extraction: freeze the pretrained layers completely and train only the new head. It’s fast and works well with small datasets. This is the main approach in this article.Fine-tuning: after the head has trained, unfreeze some of the top pretrained layers and train them with a very small learning rate. This can improve accuracy further, but it carries a higher risk of overfitting and of damaging the pretrained weights.Start with feature extraction. Fine-tune only if you need more.Step 0: Meet the pretrained model (the goldfish test)Before building anything, I wanted to see what the pretrained model could already do. I loaded a MobileNetV2 classifier from TensorFlow Hub, resized a goldfish photo to 224×224, scaled it to the 0–1 range, and asked for a prediction:pythonimport numpy as npimport PIL.Image as Imageimport tensorflow_hub as hubimport tf_kerasimg_size = (224, 224)classifier = tf_keras.Sequential([ hub.KerasLayer( "https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4", input_shape=img_size + (3,) )])img = Image.open("goldfish.jpg").resize(img_size)x = np.array(img) / 255.0result = classifier.predict(x[np.newaxis, ...])label_index = np.argmax(result[0], axis=-1)Then I matched the predicted index against the ImageNet label file. The model recognised the goldfish without a single line of training from me.Why did I use tf_keras? With TensorFlow 2.16+ and Keras 3, hub.KerasLayer needs the legacy Keras package. That's a very common error in Colab, and importing tf_keras is the fix.But this classifier can only choose among ImageNet’s 1,000 categories. The label list has “daisy”, but no rose, tulip, sunflower or dandelion class. To classify my flowers I needed the model’s knowledge, not its final answer.Step 1: Load and prepare the flower datasetI used the flower photos dataset from TensorFlow: 3,670 images in five folders.pythonimport pathlib, cv2, numpy as np, tensorflow as tffrom sklearn.model_selection import train_test_spliturl = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"data_dir = pathlib.Path( tf.keras.utils.get_file("flower_photos", origin=url, cache_dir=".", untar=True))classes = ["roses", "daisy", "dandelion", "sunflowers", "tulips"]X, y = [], []for label, name in enumerate(classes): for path in data_dir.glob(f"**/{name}/*"): img = cv2.imread(str(path)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # OpenCV loads BGR X.append(cv2.resize(img, (224, 224))) y.append(label)X, y = np.array(X), np.array(y)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)Two details matter here:The photos come in different sizes, but a network needs a fixed input shape. Every image is resized to 224×224, the size MobileNetV2 expects.I split into train and test before doing anything else. With the default split, that gives 2,752 training images and 918 test images. The test set stays untouched until the very end.Step 2: Load the base model without its head and freeze itpythonbase = tf.keras.applications.MobileNetV2( input_shape=(224, 224, 3), include_top=False, # remove the ImageNet classifier weights="imagenet" # keep the pretrained knowledge)base.trainable = False # feature extraction: freeze everythingmodel = tf.keras.Sequential([ base, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(5) # one output per flower class])model.summary()Let’s break this down:include_top=False cuts off the 1,000-class classifier and leaves only the feature extractor.weights="imagenet" loads what the network learned from 1.28 million images.base.trainable = False is the most important line in the whole project. It stops the pretrained weights from being changed.GlobalAveragePooling2D squashes each feature map into a single number, giving a compact 1,280-value summary of the image.Dense(5) is the only new part.Now look at model.summary(). The base has about 2.26 million parameters, all frozen. The new head has only 6,405 trainable parameters (1,280 × 5 weights plus 5 biases).I’m training roughly 6,000 parameters instead of 2,000,000. That’s why a small dataset is enough.Step 3: Preprocess correctly and trainMobileNetV2 in Keras expects pixel values in the range [-1, 1], which preprocess_input handles:pythonfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_inputX_train_p = preprocess_input(X_train.astype("float32"))X_test_p = preprocess_input(X_test.astype("float32"))model.compile( optimizer="adam", loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])model.fit(X_train_p, y_train, epochs=5)model.evaluate(X_test_p, y_test)from_logits=True is there because the last layer has no softmax. It outputs raw scores, and the loss function handles the conversion.The resultsEven in the middle of the very first epoch (batch 45 of 86), the running training accuracy was already around 70% [UPDATE with your final numbers].After training, my accuracy on the untouched test set was [YOUR TEST ACCURACY]%, after only [N] epochs [ADD your own numbers, and a training curve screenshot if you can].For a network that had never seen these flower classes before, that’s the power of borrowed knowledge.Optional Step 4: Fine-tune the top layersIf you want more accuracy, unfreeze the last few layers and train with a much smaller learning rate:pythonbase.trainable = Truefor layer in base.layers[:-30]: # keep early layers frozen layer.trainable = Falsemodel.compile( optimizer=tf.keras.optimizers.Adam(1e-5), # tiny learning rate loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])model.fit(X_train_p, y_train, epochs=5)You must recompile after changing trainable, or the change won't take effect. Also read the Keras fine-tuning guide's advice about BatchNorm layers before unfreezing a large part of the network.5 transfer learning pitfalls (that quietly ruin results)1. Forgetting to freeze the base. Without base.trainable = False, you're training all 2.26 million parameters with a large learning rate. That can wipe out the pretrained knowledge you came for.2. Wrong preprocessing. The TF Hub MobileNetV2 model expects inputs in [0, 1]. The Keras applications version expects [-1, 1]. Same architecture, different scaling. Use the right one for your source.3. RGB vs BGR. OpenCV loads images as BGR, but pretrained models were trained on RGB. Convert with cv2.cvtColor or the colours are wrong.4. Off-by-one labels. The TF Hub classifier outputs 1,001 scores, and index 0 is a “background” class. Match it against a label file with the same 1,001 entries.5. Leaky evaluation. Split into train and test before any augmentation or tuning, and touch the test set once. I covered this in detail in my article on data augmentation.When transfer learning is the wrong toolTransfer learning isn’t magic. Think twice when:Your data is very different from the pretrained data (for example, unusual sensor data), so the borrowed features may not fit.You have a huge dataset, where training from scratch may be worth it.You have strict model-size or licensing limits that rule out the available pretrained models.Even then, it’s worth a quick experiment. A frozen-base baseline takes minutes.Your transfer learning checklistDo I have too little data to train from scratch?Is my task similar enough to the pretrained data?Did I remove the old head (include_top=False)?Did I freeze the base (trainable = False)?Am I using the correct preprocessing and colour order?Did I split the data before anything else?Am I evaluating on an untouched test set?Frequently asked questionsWhat is transfer learning in deep learning? It’s reusing a model trained on a large dataset as the starting point for a new task, so you need far less data and training time.What’s the difference between feature extraction and fine-tuning? Feature extraction freezes the pretrained layers and trains only a new head. Fine-tuning also unfreezes some pretrained layers and trains them gently.Why freeze the pretrained layers? To protect what they learned from ImageNet while your new head is still random. Updating them early can damage them.Which pretrained model should I choose? MobileNetV2 is small and fast, so it’s a great starting point. Larger models such as ResNet, EfficientNet or ConvNeXt can be more accurate but cost more to run.Final thoughtThe biggest lesson from this project is that you don’t always need more data or a bigger model. Sometimes you need better starting knowledge.Transfer learning turns a 3,670-photo dataset into a working image classifier, and the same idea powers modern NLP and computer vision systems far beyond this example.If this helped you, clap 👏 (you can clap up to 50 times), follow for more practical deep learning, and tell me in the comments: which pretrained model would you try next, and on what data?The full notebook is here: GITHUBTransfer Learning with MobileNetV2 in Keras: A Practical Guide was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.