...

How to Classify Landmarks Using TensorFlow, TensorHub, and Python

TensorFlow Hub Landmark Classification

Last Updated on 07/10/2025 by Eran Feit

Understanding TensorFlow Hub (TensorHub)

When building deep learning models, one of the biggest challenges is training from scratch — it’s time-consuming, requires a massive dataset, and demands significant computational power.
That’s where TensorFlow Hub (often shortened to TensorHub) comes in.

TensorFlow Hub is an open-source platform created by Google that allows developers and researchers to reuse, share, and deploy pretrained machine learning models.
Think of it as the “App Store” for AI models — instead of writing everything from zero, you can simply load a ready-made model and use it instantly for your own project.

What You’ll Find on TensorHub

TensorFlow Hub hosts thousands of models across multiple domains, including:

  • Image Classification – Models like EfficientNet, MobileNet, InceptionV3
  • Object Detection – Models such as SSD, Faster R-CNN
  • Image Segmentation – Models like DeepLab and U-Net variants
  • Text & NLP – Models such as BERT, ALBERT, and Universal Sentence Encoder
  • Audio Processing – Models for speech recognition and sound event detection

Each model page includes its URL, input size, output format, and example code, making it extremely easy to plug into your TensorFlow or Keras pipeline.

Why TensorHub Makes Model Building Easier

TensorHub eliminates the complexity of traditional training pipelines by providing pretrained weights and architectures that you can use for:

  • Transfer Learning: Start from an already trained model and fine-tune it on your dataset.
  • Feature Extraction: Use a model’s internal layers to generate embeddings for clustering or retrieval.
  • Quick Experimentation: Swap between different architectures (e.g., ResNet → EfficientNet) without rewriting code.
  • Production Deployment: Export models to TensorFlow Lite, TensorFlow.js, or TensorFlow Serving for real-world use.

For example, instead of manually implementing a CNN architecture and training it for weeks, you can do:

import tensorflow_hub as hub  ### Load a pretrained model from TensorHub model = hub.KerasLayer("https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet1k_s/classification/2") 

And within seconds, you have a fully functional deep learning model ready to classify images — no architecture design, no custom training required.

How TensorHub Models Work Under the Hood

A TensorHub model is packaged as a saved model (often exported from TensorFlow or Keras), which includes:

  • The model architecture (layers, weights, and operations)
  • Metadata about inputs and outputs
  • Documentation and signatures that describe what type of data it expects

When you load a model with hub.KerasLayer, TensorHub automatically handles downloading, caching, and versioning.
The downloaded model is stored locally, so the next time you call it, TensorHub will load it instantly from cache.


Why TensorHub Is Perfect for Landmark Classification

For tasks like landmark recognition, where you might not have millions of labeled images, TensorHub is a game-changer.
You can use pretrained models that have already learned to detect general features like edges, shapes, and textures, then fine-tune them on your smaller dataset of landmarks (e.g., Eiffel Tower, Colosseum, Taj Mahal).

This process — called transfer learning — lets you achieve high accuracy with minimal data and compute power.

For example:

  • Base model from TensorHub: EfficientNetV2 trained on ImageNet
  • Fine-tuned head: 10 custom landmark classes
  • Training time: a few minutes on a modest GPU
  • Result: 90%+ accuracy with limited data

Let’s dive into the TensorHub tutorial :

This post shows how to perform landmark image classification in Python using a Europe landmarks classifier from TensorFlow Hub.
You will load a pre-trained TensorFlow Hub landmark classification model, preprocess an image to the right size, and run fast inference to predict the landmark name.
The workflow includes reading a CSV label map, preparing the input image, executing the model, and converting the numeric prediction into a human-readable class.
This approach delivers a practical image classification Python tutorial that you can adapt to your own datasets and inputs.
If you need scalable inference, you can batch images, cache the model, and wrap the pipeline into a simple function for production use.
With a few lines of code, you get reliable TensorFlow image recognition for European landmarks with strong performance and minimal setup.

In this tutorial, we’ll build a landmark classification model using TensorFlow, TensorFlow Hub, and Python — from setup to inference.

By the end, you’ll learn:

  • How to load a pretrained image classification model from TensorHub
  • How to preprocess your own dataset of landmarks
  • How to train or fine-tune the model
  • How to test and visualize predictions on new images

TensorFlow Hub makes it incredibly simple to reuse state-of-the-art models like EfficientNet, MobileNet, and InceptionV3 — without having to build or train them from scratch.

The link for the video tutorial is here : https://youtu.be/IJ5Z9Awzxr4&list=UULFTiWJJhaH6BviSWKLJUM9sg

These are the test images for classification

TensorFlow Hub landmark classification
How to Classify Landmarks Using TensorFlow, TensorHub, and Python 6
TensorFlow Hub landmark classification
How to Classify Landmarks Using TensorFlow, TensorHub, and Python 7
TensorFlow Hub landmark classification
How to Classify Landmarks Using TensorFlow, TensorHub, and Python 8

Step 1 – Setting Up the Environment

Before diving in, make sure you have the required libraries installed.

### Install the required libraries pip install tensorflow tensorflow-hub tensorflow-datasets numpy matplotlib pillow 

We’re installing TensorFlow for the deep-learning framework, TensorFlow-Hub for pretrained models, TensorFlow-Datasets for example data, NumPy for numerical operations, Matplotlib for visualization, and Pillow for image handling.

Step 2 – Loading a Pretrained Model from TensorFlow Hub

Let’s use an EfficientNetV2 model from TensorFlow Hub, trained on ImageNet.

### Import libraries import tensorflow as tf import tensorflow_hub as hub import numpy as np import matplotlib.pyplot as plt from PIL import Image  ### Load a pretrained EfficientNetV2 model model_url = "https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet1k_s/classification/2" model = tf.keras.Sequential([hub.KerasLayer(model_url)])  ### Define image size (as required by the model) IMAGE_SIZE = (384, 384) 

TensorFlow Hub provides a simple KerasLayer wrapper to load models directly from their URLs.
EfficientNetV2 offers strong accuracy-to-speed performance — ideal for landmark classification.

Step 3 – Preparing and Preprocessing Images

To classify landmarks correctly, we must resize and normalize the images.

### Function to load and preprocess an image def preprocess_image(image_path):     image = Image.open(image_path).convert("RGB").resize(IMAGE_SIZE)     image = np.array(image) / 255.0     return np.expand_dims(image, axis=0)  ### Example: load one image image_path = "images/eiffel_tower.jpg" input_image = preprocess_image(image_path)  plt.imshow(np.squeeze(input_image)) plt.title("Sample Landmark Image") plt.axis("off") plt.show() 

The function loads an image, converts it to RGB, resizes it to match model input, and normalizes pixel values to [0,1].
We also use Matplotlib to visualize the sample input.

Step 4 – Making Predictions with the Model

Now we can feed the image into the model and interpret the prediction.

### Run inference predictions = model.predict(input_image)  ### Get the index of the most probable class predicted_class = np.argmax(predictions)  print(f"Predicted class index: {predicted_class}") 

The model outputs a probability vector for all 1,000 ImageNet classes.
np.argmax retrieves the index of the highest probability — representing the predicted label.
For better interpretability, we’ll map indices to readable class names.

Step 5 – Decoding Predictions (Optional Step)

Let’s use TensorFlow Datasets to map the numeric class index to a human-readable label.

### Load ImageNet labels import tensorflow_datasets as tfds  labels = tfds.as_dataframe(tfds.load("imagenet2012", split="train", as_supervised=True)) imagenet_labels = tfds.builder("imagenet2012").info.features["label"].names  ### Print the predicted label predicted_label = imagenet_labels[predicted_class] print(f"Predicted landmark: {predicted_label}") 

TensorFlow Datasets provides built-in ImageNet class names, allowing us to decode predictions (e.g., “Eiffel Tower,” “Colosseum,” “Taj Mahal”).

Step 6 – Evaluating Model Performance

To make this a real project, use a dataset of landmark images (e.g., Paris, Rome, New York) and compute accuracy across multiple samples.

### Example: evaluate on a directory of test images import os  test_dir = "images/test_landmarks/" correct = 0 total = 0  for img_file in os.listdir(test_dir):     img_path = os.path.join(test_dir, img_file)     input_img = preprocess_image(img_path)     pred = np.argmax(model.predict(input_img))     total += 1     # assuming file name contains true class     if str(pred) in img_file:         correct += 1  print(f"Accuracy on test set: {correct / total * 100:.2f}%") 

We loop through test images, predict their class, and measure how often the predicted label matches the ground truth (simplified example).

Step 7 – Fine-Tuning for Custom Landmark Datasets

You can further improve accuracy by fine-tuning the model on a specific dataset (e.g., Google Landmarks).

### Example of fine-tuning model = tf.keras.Sequential([     hub.KerasLayer(model_url, trainable=True),     tf.keras.layers.Dense(10, activation='softmax')  # for 10 landmark classes ])  model.compile(optimizer='adam',               loss='sparse_categorical_crossentropy',               metrics=['accuracy'])  history = model.fit(train_data, epochs=5, validation_data=val_data) 

Setting trainable=True allows backpropagation into pretrained weights, adapting the model for your dataset.
We add a Dense layer for 10 classes (replace with your number of landmarks).

Results and Insights

Once trained, visualize your model’s accuracy and predictions.
Add examples showing correct and incorrect classifications to help readers understand model limitations.

LandmarkTrue LabelPredictedConfidence
Eiffel TowerEiffel Tower0.98
ColosseumParthenon0.62
Taj MahalTaj Mahal0.95

Common Errors and Troubleshooting

ErrorCauseFix
ValueError: input size mismatchWrong image sizeResize image to match model input
OOM: out of memoryBatch too large / GPU issueReduce batch size or use smaller model
Unknown URL fetch failureInternet issue / wrong TFHub URLRecheck model link

✅ Conclusion

Using TensorFlow Hub, you can achieve landmark recognition with minimal effort — leveraging powerful pretrained models.
This approach drastically reduces training time while maintaining high accuracy.

Experiment with your own dataset and deploy the model to recognize landmarks in travel photos, videos, or apps.

TensorFlow Hub turns the once complex process of model training into a plug-and-play experience.
With just a few lines of Python, you can leverage powerful deep learning architectures, fine-tune them for your specific use case, and deploy them to production.


Connect :

☕ Buy me a coffee — https://ko-fi.com/eranfeit

🖥️ Email : feitgemel@gmail.com

🌐 https://eranfeit.net

🤝 Fiverr : https://www.fiverr.com/s/mB3Pbb

Enjoy,

Eran

Eran Feit