Pretraining learns model parameters from input data before adapting them to a downstream task. An unsupervised task supplies its own prediction targets, so training can use text without manually supplied task labels. The learned parameters can then be transferred to a task such as review classification. section 14.5.4 section 14.6
Pretraining word embeddings for movie reviews
A review classifier can overfit its labeled examples before it learns a good word embedding. Instead, combine training reviews with the IMDb dataset’s 25,000 additional unlabeled reviews and pretrain the embedding separately. A continuous bag-of-words (CBOW) task predicts a missing word from its neighbors: given “sail,” “wave,” and “mast,” a plausible target might be “boat.” section 14.5.3 section 14.5.4
A practical CBOW workflow:
- Reuse the classifier’s vocabulary and tokenize reviews without padding. Slide a window over each review; use the middle word as the target and the surrounding words as input. section 14.5.4
- Embed the surrounding token IDs, average their vectors, and predict the middle token with a softmax layer. Train using sparse categorical cross-entropy. section 14.5.4
- Transfer the learned embedding parameters to the downstream sequence model, then train for the labeled task. section 14.5.4 section 14.6
Listing 14.25 Preprocessing our IMDb data for pretraining a CBOW model
context_size <- 4L #1
window_size <- context_size + 1L + context_size #2
window_data <- function(token_ids) {
windows <- tf$signal$frame(
token_ids,
frame_length = window_size,
frame_step = 1L
)
tensor_slices_dataset(windows)
}
split_label <- function(window) {
.[left, label, right] <-
tf$split(window, c(context_size, 1L, context_size))
bag <- tf$concat(tuple(left, right), axis = 0L)
tuple(bag, label)
}
dataset <- text_dataset_from_directory("aclImdb/train", batch_size = NULL) #3
dataset <- dataset |>
dataset_map(\(x, y) x, num_parallel_calls = 8) |> #4
dataset_map(tokenize_no_padding, num_parallel_calls = 8) |> #5
dataset_interleave(window_data) |> #6
dataset_map(split_label, num_parallel_calls = 8) #7Found 70000 files belonging to 3 classes. #7
The preprocessing pipeline creates context-and-target pairs from review text without using sentiment labels. section 14.5.4
Listing 14.26 Building a CBOW model
hidden_dim <- 64 cbow_embedding <- layer_embedding( input_dim = max_tokens, output_dim = hidden_dim ) inputs <- keras_input(shape = c(2 * context_size), dtype = "int32") outputs <- inputs |> cbow_embedding() |> layer_global_average_pooling_1d() |> layer_dense(max_tokens, activation = "softmax") cbow_model <- keras_model(inputs, outputs) cbow_model |> compile( optimizer = "adam", loss = "sparse_categorical_crossentropy", metrics = "sparse_categorical_accuracy" )cbow_model Model: "functional" ┌─────────────────────────────────┬────────────────────────┬───────────────┐ │ Layer (type) │ Output Shape │ Param # │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ input_layer_4 (InputLayer) │ (None, 8) │ 0 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ embedding_1 (Embedding) │ (None, 8, 64) │ 1,920,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ global_average_pooling1d │ (None, 64) │ 0 │ │ (GlobalAveragePooling1D) │ │ │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ dense_4 (Dense) │ (None, 30000) │ 1,950,000 │ └─────────────────────────────────┴────────────────────────┴───────────────┘ Total params: 3,870,000 (14.76 MB) Trainable params: 3,870,000 (14.76 MB) Non-trainable params: 0 (0.00 B)
This R/Keras model learns a 64-dimensional embedding while predicting the missing word. section 14.5.4
Listing 14.27 Training the CBOW model
dataset <- dataset |> dataset_batch(1024) |> dataset_cache() cbow_model |> fit(dataset, epochs = 4)
The training step batches and caches the prepared data, then fits the CBOW model for four epochs. section 14.5.4
Another pretraining task is next-token prediction: a language model learns to guess the next token in a sequence. GPT combined this task with a Transformer and was subsequently fine-tuned for multiple text classification tasks. A single text sequence is sufficient for pretraining; curated input-output pairs are not required. section 16.1 section 16.2.1
When adapting a pretrained model, match its input conventions. For example, RoBERTa fine-tuning uses the pretrained tokenizer and packs sequences with start, end, and padding tokens. KerasHub’s StartEndPacker can add these tokens and trim long sequences. section 15.4.3
Large-scale pretraining can be expensive in both compute and energy, making reuse of pretrained models attractive. With a fixed compute budget, increasing model size competes with training on more data; deployment cost and the availability of high-quality data also matter. section 16.3 section 16.5













