Computers Need Numbers
A neural network cannot read words. We must convert text into numbers first. The usual steps are: clean the text, split it into tokens (words), give each token a number from a vocabulary, and make all sequences the same length.
| Step | Example |
| Raw text | I love Keras! |
| Lowercase and clean | i love keras |
| Tokenize | ['i', 'love', 'keras'] |
| To integers | [5, 12, 87] |
| Pad to length 6 | [5, 12, 87, 0, 0, 0] |
Using TextVectorization
python
import keras
from keras import layers
texts = ["I love deep learning",
"Keras makes deep learning easy",
"I hate bugs"]
vectorizer = layers.TextVectorization(
max_tokens=1000, # vocabulary size
output_mode="int",
output_sequence_length=6 # pad or cut to 6 tokens
)
vectorizer.adapt(texts) # build the vocabulary from the data
print(vectorizer.get_vocabulary()) # ['', '[UNK]', 'learning', 'deep', 'i', ...]
print(vectorizer(["I love Keras"])) # a row of 6 integers
- Index 0 is reserved for padding
- Index 1 is
[UNK] for words not in the vocabulary
adapt() learns the vocabulary from your training text only
Tip: Call adapt() only on training text. Using test text would leak information, just like with scalers.
Bag of Words Option
python
bow = layers.TextVectorization(max_tokens=1000, output_mode="count")
bow.adapt(texts)
print(bow(["deep deep learning"])) # counts per word
Bag of words ignores word order. It is simple and a strong baseline for classification.
Sequences with pad_sequences
If you tokenize by yourself, you can pad the sequences with a helper.
python
sequences = [[5, 12, 87], [3, 4], [9, 8, 7, 6, 5]]
padded = keras.utils.pad_sequences(sequences, maxlen=4, padding="post", truncating="post")
print(padded)
# [[ 5 12 87 0]
# [ 3 4 0 0]
# [ 9 8 7 6]]
Put the Vectorizer Inside the Model
python
model = keras.Sequential([
keras.Input(shape=(1,), dtype="string"),
vectorizer,
layers.Embedding(input_dim=1000, output_dim=16),
layers.GlobalAveragePooling1D(),
layers.Dense(1, activation="sigmoid"),
])
Now the model accepts raw text strings and you do not need a separate preprocessing step in production. The Embedding layer is explained in the next lesson.
Good practice: Limit the vocabulary to the 10,000 to 20,000 most common words and set a sequence length that covers most of your texts.
Conclusion
Text must become integers before it enters a network. TextVectorization does cleaning, tokenizing, indexing and padding in one layer.
Quick Summary: Use TextVectorization with adapt(), keep index 0 for padding and fix the sequence length.