Sitemap
Anthony Sun

Anthony Sun

Experienced data scientist, tech enthusiast, and proud father of two, passionate about leveraging technology to solve real-world challenges.

Word Embedding from Scratch

Summary

In natural language processing (NLP), it is essential to represent words or sub-words (also called tokens) numerically so that mathematical operations can be performed efficiently. This numerical representation enables computers to process, analyse, and generate human language.

Before the introduction of word embeddings, traditional methods such as one-hot encoding and TF-IDF (Term Frequency-Inverse Document Frequency) were commonly used to represent words in a machine-readable format.

  • One-hot encoding: Each word in the vocabulary is represented as a unique vector where only one element is 1, and all others are 0.
apple  = [1, 0, 0]
banana = [0, 1, 0]
cherry = [0, 0, 1]
  • TF-IDF (Term Frequency-Inverse Document Frequency): Measures the importance of a word in a document relative to a corpus. It assigns a weight to each word based on how frequently it appears.

Word embeddings overcome these limitations by representing words as dense, continuous-valued vectors in a multi-dimensional space. Instead of arbitrary one-hot vectors, embeddings are learned from large text corpora, capturing meaningful relationships between words.

Semantic Meaning: Words with similar meanings (e.g., “king” and “queen”) are close together in vector space, while unrelated words (e.g., “king” and “apple”) are far apart.

This means that if you take the vector for “king”, subtract the vector for “man”, and add the vector for “woman”, you end up near the vector for “queen”. This shows that embeddings capture gender relationships.

Press enter or click to view image in full size

Key Advantages of Word Embeddings

  • Captures Context & Meaning: Unlike one-hot encoding, embeddings reflect word similarity and relationships.
  • Efficient Representation: Dense vectors (e.g., 300-dimensional) reduce computational cost compared to sparse one-hot vectors.
  • Generalises Better: Pretrained embeddings (e.g., Word2Vec, GloVe, FastText) can be used across multiple NLP tasks.

In summary, word embeddings revolutionised NLP by providing a way to represent words mathematically while preserving meaning, leading to better machine translation, sentiment analysis, question-answering, and more. 🚀

Training Word Embedding

Methods

Word embeddings are learned from large text corpora using unsupervised learning methods. Two of the most popular approaches for training word embeddings:

  • Skip-gram, the goal is to predict the context words given a target word. For example, in the sentence “The king rules the country,” given the word “king” as the target, the Skip-gram model tries to predict the words “the”, “rules”, “the”, and “country” as the context. This method works well with large datasets and is effective at capturing relationships between words, especially for infrequent words. The Skip-gram model learns to represent the target word in such a way that it predicts surrounding words accurately, helping the model build meaningful word embeddings.
  • Continuous Bag of Words (CBOW) works the other way around. It predicts the target word from its context words. In the same example, given the context words [“the”, “rules”, “the”, “country”], the CBOW model tries to predict the target word “king”. CBOW is faster to train compared to Skip-gram, especially with smaller datasets, as it takes the context words as input and averages their embeddings to predict the target. Both models ultimately aim to learn word representations where semantically similar words are positioned closely in the vector space.

We will go through the CBOW method for now, and later I may add skip-gram into the same article.

Step 1 — Preparation

  1. The libraries we will need are: nltk, tensorflow, sklearn and matplotlib (for visualisation)
  2. Get Data: We need to firstly download some text for training our model. We will use Project Gutenberg Book.
  3. Preprocessing: We will want to cleans the books a bit, removing unnecessary special characters, and stop-words. (they usually do not contribute too much)
# =============================================
# Download Required NLTK Datasets
# =============================================
nltk.download("gutenberg")
nltk.download("punkt")
nltk.download("stopwords")
nltk.download("punkt_tab")

# =============================================
# Load & Preprocess Text Data
# =============================================
def load_gutenberg_text():
"""Loads all books from the NLTK Gutenberg dataset and concatenates them into a single text corpus."""
corpus = ""
for file_id in gutenberg.fileids():
corpus += gutenberg.raw(file_id) + "\n\n" # Add spacing between books
return corpus

def preprocess_text(corpus):
"""Tokenizes text, removes punctuation and stopwords, and converts to lowercase."""
stop_words = set(stopwords.words("english"))
important_words = {"i", "he", "she", "we", "they", "you"} # Keep personal pronouns
filtered_stopwords = stop_words - important_words # Remove other stopwords

tokens = word_tokenize(corpus) # Tokenize text
tokens = [word.lower() for word in tokens if word.isalnum() and word not in filtered_stopwords] # Clean tokens
return tokens

# Load and preprocess text
corpus = load_gutenberg_text()
tokens = preprocess_text(corpus)

# Print the 10 most common words
word_counts = Counter(tokens)
print("Most common words:", word_counts.most_common(10))

The code is quite self-explanatory: we download necessary packages from NLTK; then we iterate through each book in the collection and built up the corpus load_gutenberg_text() ; then we pre-process. Note that we’ve kept some pronouns as they will be useful for conveying information.

Get Anthony Sun’s stories in your inbox

Join Medium for free to get updates from this writer.

Finally we counted top 10 most common words, the following is the output:

Most common words: [('i', 30209), ('he', 25839), ('and', 16570), 
('you', 16305), ('they', 13088), ('shall', 11679), ('said', 9427),
('she', 9060), ('unto', 9010), ('lord', 8585)]

Step 2 — Generate Training Data

We will firstly build up our vocabulary, basically create a unique numeric id for each of the token. We also add <PAD> and <OOV>. PAD is used to PAD our training data to ensure uniform input length. OOV (out of vocabulary) is used to handle token not in vocabulary.

Take following string as example The King rules the country. The vocab will be like below:

+---------+-------+
| Word | Index |
+---------+-------+
| <PAD> | 0 |
| <OOV> | 1 |
| the | 2 |
| king | 3 |
| rules | 4 |
| country | 5 |
+---------+-------+
def build_vocab(tokens, max_vocab_size=5000, min_freq=5):
"""Creates word-to-index and index-to-word mappings with OOV handling."""
word_counts = Counter(tokens)

# Filter words by minimum frequency
filtered_words = {word: count for word, count in word_counts.items() if count >= min_freq}

# Sort words by frequency and keep only the most common
most_common_words = sorted(filtered_words, key=filtered_words.get, reverse=True)[:max_vocab_size]

# Special tokens
word_to_ix = {'<PAD>': 0, '<OOV>': 1}

# Assign indices to words
word_to_ix.update({word: i + 2 for i, word in enumerate(most_common_words)})
ix_to_word = {i: word for word, i in word_to_ix.items()}

# ✅ Use defaultdict to handle OOV words
word_to_ix = defaultdict(lambda: 1, word_to_ix) # Default to index 1 (OOV)

return word_to_ix, ix_to_word

# Example usage
max_vocab_size = 5000 # Ensure vocabulary size is defined
word_to_ix, ix_to_word = build_vocab(tokens, max_vocab_size = max_vocab_size, min_freq=5)
vocab_size = len(word_to_ix)
print(f"Vocabulary Size: {vocab_size}")

Use the same logic, we will build the vocabulary. Each will be assigned an ID. We will add PAD and OOV in the front.

Step 3- Generate Training Data

The training data for CBOW, as described earlier will be context words and target word. Where context word are words surrounding the target word. For training, each word in our token set will be target words. Using previous example (“The king rules the country”) with a context window of 2, the context and target training pair will be as follows:

Words:
+-------------+-------------------------------+
| Target Word | Context Words |
+-------------+-------------------------------+
| the | king, rules, <PAD>, <PAD> |
| king | the, rules, the, <PAD> |
| rules | the, king, the, country |
| the | rules, country, <PAD>, <PAD> |
| country | the, rules, <PAD>, <PAD> |
+-------------+-------------------------------+

Actual output:
+-------------+----------------------+
| Target Index | Context Indices |
+-------------+----------------------+
| 2 | 3, 4, 0, 0 |
| 3 | 2, 4, 2, 0 |
| 4 | 2, 3, 2, 5 |
| 2 | 4, 5, 0, 0 |
| 5 | 2, 4, 0, 0 |
+-------------+----------------------+

Note, the context size is 2*context_window .

The following is python code to generate data. In this case, we used a generator to efficiently use memory. Assuming we have a vocab of 5000, the context window size of 5 and a batch of 128. The memory usesage can be quite high. context_mem = batch_size*window_size*2*vocab_size and target_mem = batch_size * vocab_size . Also noting we did one-hot encoding on the target, but not context. This is also to save memory. The one-hot encoding for context will be done on the fly to save memory.

def cbow_data_generator(tokens, word_to_ix, window_size=5):
"""Generates (context, target) pairs for CBOW training (yields raw indices)."""
for idx in range(len(tokens)):

context = [
word_to_ix.get(tokens[i], word_to_ix["<OOV>"])
for i in range(max(0, idx - window_size), min(len(tokens), idx + window_size + 1))
if i != idx
] # Context words as word indices

target = word_to_ix.get(tokens[idx], word_to_ix["<OOV>"]) # Target word as index

# Ensure fixed-size context (pad if necessary)
while len(context) < 2 * window_size:
context.append(word_to_ix["<PAD>"])

vocab_size = len(word_to_ix) # Ensure vocabulary size is defined
target_one_hot = tf.one_hot(tf.cast(target, tf.int32), depth=vocab_size)

yield np.array(context, dtype=np.int32), target_one_hot.numpy() # Yield context and target

# Define parameters
window_size = 5
embedding_dim = 10

# Keep dataset as word indices, apply one-hot encoding inside the model
dataset = tf.data.Dataset.from_generator(
lambda: cbow_data_generator(tokens, word_to_ix, window_size),
output_signature=(
tf.TensorSpec(shape=(2 * window_size,), dtype=tf.int32), # Context words (indices)
tf.TensorSpec(shape=(vocab_size), dtype=tf.int32) # Target (index)
)
)

Step 4 — Building Model

The model will consist 5 layers, we will go through each layer:

  1. Input Layer: It’s self explanatory, our input will be context words, which will be a shape of batch_size, 2*context_window.
  2. Lambda Layer: The input are list ID’s, we will need to perform one-hot encoding. It is most efficient if we do it during training as part of the model, as the memory will be released as soon as calculation is done. Following one hot, we will have a shape of batch_size, 2*context_window, vocab_size
  3. Dense Layer: Here we will a dense layer, acting as an embedding lookup to train word embedding, which are the weights. The shape of the weights (embedding) will be vocab_size, embedding_dim , and output will be batch_size, 2*context_window, embedding_dim . As can be seen, the wright will have an word vector for each vocab.
  4. Mean Pooling Layer: The assumption is the average context word (overall meaning) will be similar to target word. So this is a pure mathematical operation to get the averge of the previous step. mean_pooling = (embedding 1 + embedding 2 ... embedding_n) / 2*context_window
  5. Output Dense with Softmax: Lastly, we will predict the target word with a softmax classifier. Note target is one-hot encoded, and output will be probabily distribution of the vocabulary.

Putting it all together:

import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Lambda
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam

def build_cbow_model(vocab_size, embedding_dim, window_size):
"""Builds a CBOW model where one-hot encoding is done inside the model for both input and output."""

input_layer = Input(shape=(2 * window_size,)) # Input: word indices (NOT one-hot)

# Convert word indices to one-hot dynamically (for input)
one_hot_input = Lambda(lambda x: tf.one_hot(tf.cast(x, tf.int32), depth=vocab_size))(input_layer)

# Dense layer simulating embedding lookup (trainable weight matrix)
dense_embedding = Dense(embedding_dim, use_bias=False)(one_hot_input) # (batch, context_size, embedding_dim)

# Mean Pooling (Averaging context word vectors)
mean_embedding = Lambda(lambda x: tf.reduce_mean(x, axis=1))(dense_embedding)

# Output Layer (Softmax for predicting target word)
output_layer = Dense(vocab_size, activation="softmax")(mean_embedding)

# Compile Model (Now Uses Standard `categorical_crossentropy`)
model = Model(inputs=input_layer, outputs=output_layer)
model.compile(loss="categorical_crossentropy", optimizer=Adam(learning_rate=0.01), metrics=["accuracy"])

return model

# ✅ No need to precompute one-hot encoding!
# Use word indices directly
model = build_cbow_model(vocab_size, embedding_dim, window_size)
model.summary()

Step 5 — Model Training

We are not going to elaborate on how training works, it’s pretty much the same for all other trainings. The code is as below, I have added a couple of callbacks:

# =============================================
# Train CBOW Model
# =============================================
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

# Build CBOW model
model = build_cbow_model(vocab_size, embedding_dim, window_size)

# Checkpoint to save best model
checkpoint = ModelCheckpoint(
filepath="cbow_best_model.h5",
monitor="loss", # Monitor training loss
save_best_only=True,
mode="min",
verbose=1
)

# Early stopping to prevent overfitting
early_stopping = EarlyStopping(
monitor="loss", # Monitor training loss (no val_loss in unsupervised training)
patience=5, # Stop if loss doesn't improve for 5 epochs
min_delta=1e-4, # Ignore very small changes
mode="min",
verbose=1
)

# Training dataset (replace with actual tf.data.Dataset)
batch_size = 128
epochs = 50 # More epochs needed for embeddings
dataset = dataset.batch(batch_size).prefetch(tf.data.AUTOTUNE)

# Train model
model.fit(
dataset,
epochs=epochs,
verbose=1,
callbacks=[checkpoint, early_stopping]
)

Visualising Result

As can be seen, when visualise a sample of words, similar words or related words are clustered close to each other. Though there are exceptions. For example, cat and dog is further apart but cat is close to the house. May be due to the text we have portrait cats always play around the house. :)

Press enter or click to view image in full size
Some words visualised using t-SNE dimension reduction technique

Of course, we only used a very small vocabulary (5000) and dimension (10) for the training. To better optimise we may want to increase these parameters, then we will need to optimise our memory usage more efficiently. Tensorflow provides an embedding layer which does exactly this, see below adjusted function and I will leave the rest of discovery to you.

def build_cbow_model_embedding_layer(vocab_size, embedding_dim, window_size):
"""Builds a CBOW model using an Embedding layer instead of one-hot encoding."""

# 🔹 Input: word indices (no need for one-hot encoding)
input_layer = Input(shape=(2 * window_size,), dtype=tf.int32) # (batch_size, context_size)

# 🔹 Embedding layer replaces one-hot + dense embedding lookup
embedding_layer = Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=2 * window_size)
embedded_context = embedding_layer(input_layer) # (batch_size, context_size, embedding_dim)

# 🔹 Mean Pooling (Averaging context word vectors)
mean_embedding = Lambda(lambda x: tf.reduce_mean(x, axis=1))(embedded_context) # (batch_size, embedding_dim)

# 🔹 Output Layer (Softmax for predicting target word)
output_layer = Dense(vocab_size, activation="softmax")(mean_embedding) # (batch_size, vocab_size)

# ✅ Define Model
model = Model(inputs=input_layer, outputs=output_layer)
model.compile(loss="categorical_crossentropy", optimizer=Adam(learning_rate=0.01), metrics=["accuracy"])

return model

Written by Anthony Sun

Experienced data scientist, tech enthusiast, and proud father of two, passionate about leveraging technology to solve real-world challenges.