Pretrained Language Models and KerasHub
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.
| Approach | Data needed | Typical IMDB accuracy |
|---|---|---|
| Embedding + pooling from scratch | Medium | 86 to 88 percent |
| LSTM from scratch | Medium | 86 to 89 percent |
| Fine-tuned BERT-style model | Small is enough | 90 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
| Task | What you need |
|---|---|
| Text generation | A causal language model preset |
| Question answering | A model fine-tuned for QA |
| Image models | KerasHub also includes image backbones |
| Embeddings for search | A 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.

