TensorFlow Hub

0.16.1 · active · verified Sat Apr 11

TensorFlow Hub (TF-Hub) is a library designed to promote the publication, discovery, and consumption of reusable parts of machine learning models. It provides a repository of pre-trained model components, facilitating transfer learning and accelerating development in various domains like image classification, text embedding, and object detection. The library is actively maintained, with its latest version being 0.16.1, and typically follows a regular release cadence to align with TensorFlow's ecosystem.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a pre-trained text embedding model from TensorFlow Hub using `hub.KerasLayer` and generate embeddings for sample text. It also shows how to integrate this `hub.KerasLayer` into a larger Keras Sequential model for transfer learning tasks like text classification.

import tensorflow as tf
import tensorflow_hub as hub

# Load a pre-trained text embedding model from TensorFlow Hub
# This model generates 128-dimensional embeddings for text inputs.
model_url = "https://tfhub.dev/google/nnlm-en-dim128/2"
embed = hub.KerasLayer(model_url, input_shape=[], dtype=tf.string, trainable=False)

# Example usage: Generate embeddings for a list of sentences
sentences = [
    "Hello TensorFlow Hub!",
    "This is a test sentence for text embedding.",
    "Machine learning is fun."
]

embeddings = embed(tf.constant(sentences))

print(f"Input sentences: {sentences}")
print(f"Generated embeddings shape: {embeddings.shape}")
print(f"First embedding (first 5 values): {embeddings[0, :5].numpy()}")

# You can then use these embeddings as input to another Keras layer
# for tasks like classification.
classifier_model = tf.keras.Sequential([
    embed,
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])
classifier_model.summary()

view raw JSON →