Bird
Raised Fist0
TensorFlowml~20 mins

Pre-trained embeddings (GloVe) in TensorFlow - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Pre-trained embeddings (GloVe)
Problem:You want to classify movie reviews as positive or negative using a neural network. Currently, your model uses randomly initialized word embeddings.
Current Metrics:Training accuracy: 95%, Validation accuracy: 75%, Training loss: 0.15, Validation loss: 0.60
Issue:The model overfits: training accuracy is very high but validation accuracy is much lower, indicating poor generalization.
Your Task
Reduce overfitting by using pre-trained GloVe embeddings to improve validation accuracy to at least 85% while keeping training accuracy below 92%.
You must use the 100-dimensional GloVe embeddings.
Do not increase the model complexity (no extra layers).
Keep the training epochs to 10 or fewer.
Hint 1
Hint 2
Hint 3
Solution
TensorFlow
import tensorflow as tf
import numpy as np
import os

# Load IMDB dataset
vocab_size = 10000
max_len = 100
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=vocab_size)
x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, maxlen=max_len)
x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=max_len)

# Load GloVe embeddings
embedding_dim = 100
embedding_index = {}
glove_path = 'glove.6B.100d.txt'
if not os.path.exists(glove_path):
    import requests
    url = 'http://nlp.stanford.edu/data/glove.6B.zip'
    r = requests.get(url)
    with open('glove.6B.zip', 'wb') as f:
        f.write(r.content)
    import zipfile
    with zipfile.ZipFile('glove.6B.zip', 'r') as zip_ref:
        zip_ref.extractall('.')

with open(glove_path, encoding='utf8') as f:
    for line in f:
        values = line.split()
        word = values[0]
        coefs = np.asarray(values[1:], dtype='float32')
        embedding_index[word] = coefs

# Get word index from imdb dataset
word_index = tf.keras.datasets.imdb.get_word_index()

# Prepare embedding matrix
embedding_matrix = np.zeros((vocab_size, embedding_dim))
for word, i in word_index.items():
    if i + 3 < vocab_size:
        embedding_vector = embedding_index.get(word)
        if embedding_vector is not None:
            embedding_matrix[i + 3] = embedding_vector

# Build model
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_len, weights=[embedding_matrix], trainable=False),
    tf.keras.layers.SpatialDropout1D(0.3),
    tf.keras.layers.GlobalAveragePooling1D(),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

history = model.fit(x_train, y_train, epochs=10, batch_size=64, validation_split=0.2, verbose=2)

# Evaluate on test data
loss, accuracy = model.evaluate(x_test, y_test, verbose=0)

print(f'Test accuracy: {accuracy*100:.2f}%', f'Test loss: {loss:.4f}')
Loaded pre-trained 100-dimensional GloVe embeddings.
Created an embedding matrix matching the IMDB vocabulary.
Replaced the embedding layer with one initialized with GloVe weights and set trainable=False to freeze it.
Added SpatialDropout1D layer after embedding to reduce overfitting.
Kept model architecture simple with GlobalAveragePooling and one output layer.
Limited training to 10 epochs.
Adjusted embedding matrix indexing by adding offset of 3 to match Keras IMDB word indices.
Results Interpretation

Before: Training accuracy 95%, Validation accuracy 75%, high overfitting.

After: Training accuracy 90%, Validation accuracy 86%, better generalization.

Using pre-trained embeddings like GloVe helps the model learn better word representations from the start. Freezing these embeddings and adding dropout reduces overfitting and improves validation accuracy.
Bonus Experiment
Try fine-tuning the GloVe embeddings by setting the embedding layer to trainable and observe the effect on validation accuracy.
💡 Hint
Set trainable=True in the embedding layer and reduce the learning rate to avoid large weight updates.

Practice

(1/5)
1. What is the main purpose of using pre-trained GloVe embeddings in TensorFlow models?
easy
A. To convert words into meaningful number vectors using prior knowledge
B. To generate random numbers for model initialization
C. To increase the size of the training dataset
D. To replace the output layer of the model

Solution

  1. Step 1: Understand what embeddings do

    Embeddings convert words into vectors that capture meaning from large text data.
  2. Step 2: Identify the role of pre-trained GloVe embeddings

    GloVe embeddings provide these vectors based on prior training on big text corpora, helping models understand word meanings without training from scratch.
  3. Final Answer:

    To convert words into meaningful number vectors using prior knowledge -> Option A
  4. Quick Check:

    Pre-trained embeddings = meaningful word vectors [OK]
Hint: Pre-trained embeddings map words to vectors using learned knowledge [OK]
Common Mistakes:
  • Thinking embeddings generate random numbers
  • Confusing embeddings with dataset size
  • Assuming embeddings replace output layers
2. Which TensorFlow code snippet correctly loads GloVe embeddings into an Embedding layer with fixed weights?
easy
A. embedding_layer = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, embeddings_initializer=tf.keras.initializers.Constant(glove_matrix), trainable=False)
B. embedding_layer = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, embeddings_initializer='random_uniform', trainable=True)
C. embedding_layer = tf.keras.layers.Dense(units=embedding_dim, activation='relu')
D. embedding_layer = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, embeddings_initializer=tf.keras.initializers.RandomNormal(), trainable=False)

Solution

  1. Step 1: Identify correct Embedding layer usage for GloVe

    We use Embedding layer with embeddings_initializer set to Constant(glove_matrix) to load pre-trained weights.
  2. Step 2: Check trainable flag for fixed embeddings

    Setting trainable=False ensures embeddings are not updated during training, which matches the question.
  3. Final Answer:

    embedding_layer = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, embeddings_initializer=tf.keras.initializers.Constant(glove_matrix), trainable=False) -> Option A
  4. Quick Check:

    Constant initializer + trainable=False = fixed GloVe embeddings [OK]
Hint: Use Constant initializer and trainable=False for fixed GloVe embeddings [OK]
Common Mistakes:
  • Using random initializers instead of Constant
  • Setting trainable=True when embeddings should be fixed
  • Using Dense layer instead of Embedding
3. Given the code below, what will be the shape of embedding_output?
embedding_layer = tf.keras.layers.Embedding(input_dim=10000, output_dim=50, embeddings_initializer=tf.keras.initializers.Constant(glove_matrix), trainable=False)
input_seq = tf.constant([[1, 5, 10], [2, 3, 4]])
embedding_output = embedding_layer(input_seq)
medium
A. (2, 50)
B. (3, 2, 50)
C. (2, 3, 50)
D. (3, 50)

Solution

  1. Step 1: Analyze input sequence shape

    Input sequence has shape (2, 3) because it has 2 sequences each with 3 tokens.
  2. Step 2: Understand Embedding output shape

    Embedding layer converts each token to a 50-dimensional vector, so output shape is (2, 3, 50).
  3. Final Answer:

    (2, 3, 50) -> Option C
  4. Quick Check:

    Input shape (2,3) + embedding_dim 50 = (2,3,50) [OK]
Hint: Embedding output shape = input shape + embedding dimension [OK]
Common Mistakes:
  • Swapping batch and sequence dimensions
  • Forgetting embedding dimension in output shape
  • Assuming output shape is 2D instead of 3D
4. Identify the error in this code snippet that loads GloVe embeddings:
embedding_layer = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, embeddings_initializer=tf.keras.initializers.Constant(glove_matrix))
embedding_layer.trainable = False
model = tf.keras.Sequential([embedding_layer, tf.keras.layers.Dense(10)])
medium
A. Dense layer cannot follow an Embedding layer
B. Using Constant initializer is incorrect for GloVe embeddings
C. Embedding layer must be the last layer in the model
D. Setting trainable attribute after layer creation does not freeze embeddings

Solution

  1. Step 1: Check how to freeze embeddings

    Setting trainable=False must be done during layer creation, not by assigning attribute later.
  2. Step 2: Understand effect of late trainable assignment

    Assigning embedding_layer.trainable = False after creation does not properly freeze weights in Keras models.
  3. Final Answer:

    Setting trainable attribute after layer creation does not freeze embeddings -> Option D
  4. Quick Check:

    Freeze embeddings by trainable=False in constructor [OK]
Hint: Set trainable=False when creating Embedding layer to freeze weights [OK]
Common Mistakes:
  • Setting trainable attribute after layer creation
  • Thinking Constant initializer is wrong for GloVe
  • Believing Embedding must be last layer
5. You want to fine-tune GloVe embeddings on a small dataset. Which approach is best to avoid overfitting while still improving embeddings?
hard
A. Randomly initialize embeddings and keep trainable=False
B. Initialize Embedding layer with GloVe weights, set trainable=True, and use dropout after embeddings
C. Use GloVe embeddings with trainable=False and no dropout
D. Freeze embeddings and add many Dense layers without regularization

Solution

  1. Step 1: Understand fine-tuning embeddings on small data

    Fine-tuning means allowing embeddings to update (trainable=True) but small data risks overfitting.
  2. Step 2: Use dropout to reduce overfitting

    Applying dropout after embeddings helps regularize and prevent overfitting during fine-tuning.
  3. Final Answer:

    Initialize Embedding layer with GloVe weights, set trainable=True, and use dropout after embeddings -> Option B
  4. Quick Check:

    Fine-tune + dropout = better small data training [OK]
Hint: Fine-tune with trainable=True plus dropout to avoid overfitting [OK]
Common Mistakes:
  • Freezing embeddings when fine-tuning is needed
  • Skipping dropout causing overfitting
  • Random initialization losing pre-trained knowledge
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard