CHAPTER 8: HANDLING TEXT DATA: TOKENIZATION, PADDING, AND VECTORIZATION (TextVectorization Layer)

Master natural language processing (NLP) pipelines in TensorFlow. Learn how to convert raw text strings into numerical tensors using the native `TextVectorization` preprocessing layer for tokenization, vocabulary indexing, and sequence padding.

πŸ“ Bridging Human Language and Numerical Tensors

Neural networks cannot process raw strings directly; text data must first be tokenized into discrete units, mapped to integer vocabulary indices, and padded to uniform lengths for batch processing. TensorFlow provides the high-performance `tf.keras.layers.TextVectorization` preprocessing layer to standardize text, build vocabulary tables, and vectorize text directly inside model graphs or `tf.data` pipelines.

1. The Text Preprocessing Pipeline
The sequential stages required to transform raw text strings into fixed-length integer index tensors.
Text Vectorization Pipeline Matrix
TEXT VECTORIZATION STAGES:
[ Raw Text Strings ] ──> [ Standardization ] (Lowercase, strip punctuation)
                                β”‚
                                β–Ό
                       [ Tokenization ] (Split strings into individual words/tokens)
                                β”‚
                                β–Ό
                       [ Vocabulary Indexing ] (Map tokens to unique integer IDs)
                                β”‚
                                β–Ό
                       [ Padding / Truncating ] (Ensure uniform tensor sequence lengths)
Architectural Definition: The `TextVectorization` layer encapsulates all text preprocessing steps into a native Keras layer that can be saved directly inside serialized model artifacts.
2. Configuring the `TextVectorization` Layer
Key configuration parameters for controlling vocabulary size, sequence output modes, and padding lengths.
TextVectorization Parameters Matrix
TEXTVECTORIZATION PARAMETERS:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ PARAMETER               β”‚ PURPOSE                            β”‚ COMMON SETTING / EXAMPLE                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ `max_tokens`            β”‚ Maximum vocabulary size.           β”‚ `max_tokens=10000`                        β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ `output_mode`           β”‚ Representation format.             β”‚ `'int'` (integer indices) or `'tf-idf'`   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ `output_sequence_length`β”‚ Fixed length for padding/truncatingβ”‚ `output_sequence_length=100`              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Insight: Setting `output_sequence_length` ensures all output tensors share an identical shape, allowing them to be batched into multi-dimensional matrices for GPU training.
3. Python Code Example: Tokenization & Vectorization with Keras
A production Python script demonstrating how to initialize, adapt, and apply the `TextVectorization` layer on sample text data.
Python (text_vectorization_demo.py)
import tensorflow as tf
from tensorflow.keras.layers import TextVectorization

def demonstrate_text_vectorization():
    # Sample corpus of text data
    training_texts = [
        "TensorFlow is an open-source machine learning platform.",
        "Deep learning models require high performance GPUs.",
        "Natural language processing enables machines to understand text."
    ]
    
    # 1. Initialize TextVectorization layer
    vectorize_layer = TextVectorization(
        max_tokens=20,
        output_mode='int',
        output_sequence_length=8
    )
    
    # 2. Adapt the layer to the training corpus (builds vocabulary dictionary)
    vectorize_layer.adapt(training_texts)
    
    # Inspect learned vocabulary
    vocab = vectorize_layer.get_vocabulary()
    print(f"[*] Learned Vocabulary (First 10 tokens):\n{vocab[:10]}")
    
    # 3. Vectorize new input sentences
    test_sentences = [
        "Deep learning models process text.",
        "TensorFlow platform for machine learning."
    ]
    
    vectorized_output = vectorize_layer(test_sentences)
    print(f"\n[+] Vectorized Output Tensors Shape: {vectorized_output.shape}")
    print(f"[+] Vectorized Output Tensors:\n{vectorized_output.numpy()}")

if __name__ == "__main__":
    demonstrate_text_vectorization()
Execution Output: [*] Learned Vocabulary (First 10 tokens): ['', '[UNK]', 'text', 'to', 'tensorflow', 'processing', 'platform', 'open-source', 'models', 'machine'] [+] Vectorized Output Tensors Shape: (2, 8) [+] Vectorized Output Tensors: [[ 8 9 12 13 2 0 0 0] [ 4 6 14 9 12 0 0 0]]
4. Handling Unknown Tokens (`[UNK]`) and Padding (`''`)
Understanding special vocabulary indices reserved for out-of-vocabulary words (`[UNK] = 1`) and padding (`0`).
Special Tokens Reference
SPECIAL VOCABULARY INDICES:
- Index `0`: Reserved for padding (`''` or mask token) to ensure sequences match `output_sequence_length`.
- Index `1`: Reserved for out-of-vocabulary (`[UNK]`) tokens encountered during inference that were not present in the adapted vocabulary.
Strategic Insight: Recognizing special index assignments (`0` for padding, `1` for unknown) is vital when configuring Embedding layers (`mask_zero=True`).
5. Best Practices for Text Preprocessing Pipelines
Software engineering standards for embedding text vectorization layers directly inside model architectures.
Text Preprocessing Best Practices Checklist
TEXT PROCESSING CHECKLIST:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ BEST PRACTICE          β”‚ IMPLEMENTATION & OBJECTIVE                                                    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Include Layer in Model β”‚ Embed `TextVectorization` directly inside your `tf.keras.Sequential` model    β”‚
β”‚                        β”‚ so raw strings can be passed directly to inference endpoints.                 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Adapt on Training Only β”‚ Always call `.adapt()` exclusively on training data to prevent data leakage   β”‚
β”‚                        β”‚ from validation or test sets into the vocabulary dictionary.                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Match Max Tokens       β”‚ Ensure `max_tokens` matches your Embedding layer input dimension correctly.   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Masterclass Rule: Embedding the `TextVectorization` layer directly into your Keras model simplifies deployment by eliminating separate client-side preprocessing code.
6. Chapter Summary & Next Steps
Reviewing text tokenization and previewing image data augmentation pipelines.
Chapter Review Checklist
CHAPTER REVIEW CHECKLIST:
1. `TextVectorization` standardizes, tokenizes, and vectorizes raw text strings into integer tensors.
2. Vocabulary adaptation builds integer mapping dictionaries while reserving index 0 for padding and 1 for `[UNK]`.
3. Integrating the vectorization layer directly into Keras models streamlines deployment.
4. Next Chapter: We cover Chapter 9 ("Image Data Augmentation & Preprocessing Pipelines").
Next Chapter Preview: In Chapter 9, we explore image preprocessing and augmentation pipelinesβ€”including resizing, normalization, random rotations, and flips.