Pretrained Language Models and KerasHub

Deep Learning with Keras and TensorFlow 10 min min read Updated: Nov 16, 2026 Advanced
Pretrained Language Models and KerasHub
Advanced Topic 9 of 9

Why Pretrained Language Models?

Models like BERT were trained on huge amounts of text, so they already understand grammar, meaning and many facts. You only fine-tune them on your small dataset. This gives much better results than training a text model from scratch.

ApproachData neededTypical IMDB accuracy
Embedding + pooling from scratchMedium86 to 88 percent
LSTM from scratchMedium86 to 89 percent
Fine-tuned BERT-style modelSmall is enough90 to 94 percent

Install KerasHub

bash pip install keras-hub

Load a Pretrained Classifier

KerasHub provides ready-made task models. The preprocessing (tokenization) is included in the model.

python import keras import keras_hub classifier = keras_hub.models.BertClassifier.from_preset( "bert_tiny_en_uncased", # a small preset, good for learning num_classes=2, ) classifier.summary()
Preset names: The available presets change over time. Check the KerasHub documentation for the current list, and try a small preset first because large models need a strong GPU.

Fine-Tune on Your Text

python # train_ds yields (text, label) batches, as in the IMDB lesson classifier.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(5e-5), metrics=["accuracy"], ) classifier.fit(train_ds, validation_data=val_ds, epochs=2)
  • Use a small learning rate (about 2e-5 to 5e-5) so you do not destroy pretrained knowledge
  • Two or three epochs are usually enough
  • Reduce the batch size if you get out of memory errors

Predict

python texts = ["A wonderful, touching film.", "I want my money back."] logits = classifier.predict(texts) print(logits.argmax(axis=-1)) # 1 = positive, 0 = negative

Other Things You Can Do

TaskWhat you need
Text generationA causal language model preset
Question answeringA model fine-tuned for QA
Image modelsKerasHub also includes image backbones
Embeddings for searchA sentence embedding model
Responsible use: Pretrained models can reflect biases in their training data. Test your model on different kinds of text before putting it in production.

Conclusion

Pretrained language models give state-of-the-art text results with little code. Start with a small preset and fine-tune gently.

Quick Summary: Load a preset with KerasHub, compile with a small learning rate and fine-tune for two or three epochs.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators