Pre-trained Models with KerasHub
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
KerasHub is the Keras library of pre-trained models. It provides model architectures, tokenizers, preprocessors and a catalogue of named checkpoints ("presets") for text, vision, audio and multimodal tasks, all as ordinary Keras layers and models that run on the TensorFlow, JAX and PyTorch backends. This page explains the API, how it compares with keras.applications, and how to fine-tune a preset. The classic keras.applications workflow is covered on Transfer Learning & Fine-Tuning; text pipelines on Text, RNNs & Embeddings; attention on Attention & Transformers. The ecosystem context is on Ecosystem & Project Status, and the Hugging Face alternative on Hub Essentials.
It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is "upcoming"), and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21, Keras 3.15 and KerasHub 0.32 (CPU) on 2026-10-31, downloading the resnet_50_imagenet and bert_base_en_uncased presets; the image example used a local synthetic image instead of the placeholder URL, and the fine-tuning example used a few synthetic reviews in place of imdb_train and imdb_test. Preset names change as checkpoints are added; check the official preset list before relying on a name.
keras.applications, KerasHub and KerasCV
| Library | Status | Scope |
|---|---|---|
|
Part of Keras itself |
A fixed set of ImageNet classifiers (ResNet, EfficientNet, MobileNet, ConvNeXt and others) with |
KerasHub ( |
Separate package, actively developed |
Backbones, tokenizers, preprocessors and task models for text, vision, audio and multimodal checkpoints, loaded by preset name. Successor of the earlier KerasNLP library. |
KerasCV |
Archived repository |
The former computer-vision library; its models and layers were consolidated into KerasHub and Keras. Do not start new projects on it. |
Older tutorials import keras_nlp or keras_cv. Use keras_hub instead; the archived KerasCV repository is kept only for reference.
Installation and backend
pip install -U keras-hub keras
Installing KerasHub pulls in TensorFlow (on Linux and macOS it depends on tensorflow-text, which requires tensorflow), because tf.data and TensorFlow string ops are used for preprocessing, even if training runs on another backend. Select the backend before importing Keras:
import os
os.environ["KERAS_BACKEND"] = "tensorflow" # or "jax", "torch"
import keras
import keras_hub
Source: https://keras.io/keras_hub/
See Keras Multi-Backend for backend selection details.
The building blocks
-
Backbone: the architecture without a task head (for example a BERT encoder or a ResNet feature extractor). It outputs features and is a
keras.Model. -
Preprocessor: converts raw input to model input: a tokenizer plus packing and padding for text, resizing and rescaling for images.
-
Task model: a backbone plus preprocessor plus task head (
ImageClassifier,TextClassifier,CausalLM,Seq2SeqLM,ObjectDetectorand so on). Task models arekeras.Modelsubclasses, sofit,predictandevaluatework as usual. -
Preset: a named checkpoint (architecture config, weights and preprocessing config), for example
"resnet_50_imagenet"or"bert_base_en_uncased".
Every class exposes from_preset(name, **overrides). Calling it on a task class loads backbone, preprocessor and (when the preset includes it) a trained head; calling it on Backbone loads only the backbone.
Example: image classification with a preset
import numpy as np
import keras
import keras_hub
classifier = keras_hub.models.ImageClassifier.from_preset(
"resnet_50_imagenet",
activation="softmax",
)
path = keras.utils.get_file(origin="https://example.com/cat.jpg") # any local or remote image
image = keras.utils.load_img(path)
preds = classifier.predict(np.array([image]))
print(keras_hub.utils.decode_imagenet_predictions(preds))
Source: https://keras.io/keras_hub/
The built-in preprocessor resizes and rescales the raw image, so the caller does not apply preprocess_input by hand, one reason to prefer KerasHub task models over wiring keras.applications yourself.
Example: fine-tuning a text classifier
import keras
import keras_hub
# imdb_train / imdb_test: tf.data.Dataset of (list of strings, integer labels), batched
classifier = keras_hub.models.BertClassifier.from_preset(
"bert_base_en_uncased",
num_classes=2, # outputs logits, matching the default from_logits=True loss
)
classifier.fit(imdb_train, validation_data=imdb_test, epochs=1)
logits = classifier.predict(["What an amazing movie!", "A total waste of time."])
print(keras.ops.softmax(logits)) # class probabilities, shape (2, 2)
Source: https://keras.io/keras_hub/
Because the preprocessor is part of the task model, you feed raw strings. The task class compiles itself with a default optimiser and a SparseCategoricalCrossentropy(from_logits=True) loss. Do not pass activation="softmax" here without compiling yourself: the default loss would then receive probabilities, and Keras warns that the output "was produced by a Softmax activation and thus does not represent logits"; call compile() yourself to change the learning rate (use a small value, in the region of 1e-5 to 5e-5 for BERT-sized encoders) and to monitor your own metrics.
Using a backbone in your own model
backbone = keras_hub.models.Backbone.from_preset("resnet_50_imagenet")
backbone.trainable = False
inputs = keras.Input(shape=(224, 224, 3))
x = backbone(inputs, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
outputs = keras.layers.Dense(10)(x)
model = keras.Model(inputs, outputs)
Source: https://keras.io/keras_hub/api/
The same freezing rules apply as for keras.applications: set trainable, call with training=False, recompile after changes; see Transfer Learning & Fine-Tuning. Whether a backbone outputs a feature map or a dictionary depends on the model family, so print backbone.output_shape or backbone.summary() before attaching a head.
Tokenizers, generation and large models
-
Text presets include a tokenizer (WordPiece, byte-pair or SentencePiece depending on the family).
Tokenizer.from_preset(name)gives you the tokenizer alone, andtokenizer("some text")returns token ids. -
Causal language models offer
generate(prompt, max_length=...)for text generation, with a configurable sampler. -
Large models (billions of parameters) need memory planning: load in lower precision with
dtype="bfloat16"where the preset supports it (see Mixed Precision) and shard across devices with the Keras distribution API (Distributed Training). -
Parameter-efficient fine-tuning with LoRA is available on KerasHub backbones through
backbone.enable_lora(rank=4)(KerasHub 0.32 signature:enable_lora(rank, target_layer_names=None)), which leaves the attention query and value projections trainable only through new low-ranklora_kernel_aandlora_kernel_bweights (forbert_base_en_uncasedthe trainable weights drop from 199 to 72). -
Many presets are hosted on Kaggle and Hugging Face; some are gated and require accepting a licence and providing credentials through environment variables. Read the licence before using a checkpoint commercially; see Choosing Models and Licences.
Checkpoints you can save and share
A fine-tuned task model can be saved in the .keras format (Saving Keras Models). KerasHub models also support save_to_preset(directory) to write a preset folder that from_preset can reload, including the tokenizer or preprocessor configuration.
Pitfalls
-
Mixing the archived
keras_cvorkeras_nlppackage names withkeras_hubin the same environment. -
Forgetting that installation brings TensorFlow in even for JAX or PyTorch training.
-
Passing already-tokenized data to a task model that expects raw strings, or the other way around when you pass
preprocessor=None. -
Assuming a preset name from a blog post still exists; list presets from the official catalogue.
-
Not recompiling after changing the learning rate or trainable state.