Word Embeddings in NLP
Natural Language Processing: Word Embeddings
Problems with One-Hot Vectors
One-hot encoding converts each word into a vector the size of the vocabulary, with a single 1 at the word's index and 0s elsewhere. While simple, this representation has serious shortcomings:
No semantic similarity: Every pair of distinct one-hot vectors has the same Euclidean distance, 2. Words like "movie" and "film" (synonyms) and "good" and "bad" (antonyms) are equally distant – the representation ignores meaning entirely.
Computational inefficiency: For a vocabulary of 500,000 words, each one-hot vector has 500,000 dimensions, leading to massive weight matrices and high computational cost.
No notion of direction: The distance between any two different words is identical, so there is no geometric structure reflecting semantic relationships.
Key takeaway: One-hot vectors fail to capture any relationship between words – they are merely identification codes, not meaningful representations.
The Need for Word Embeddings
Word embeddings are dense, low-dimensional vectors learned from data that place semantically similar words close together in vector space. They fix both problems of one-hot vectors:
Compact representation: Embeddings typically have 50–300 dimensions regardless of vocabulary size.
Semantic geometry: Similar words (e.g., "car" vs. "truck") are near each other; dissimilar words are far apart. Moreover, direction in embedding space captures relationships (e.g., "man → woman" is analogous to "king → queen").
In a properly learned embedding space, words cluster by meaning: buildings, vehicles, fruits, sports equipment all occupy distinct regions. The geometric relationship (distance and direction) encodes semantic relationship.
Beyond Standalone Embeddings: The Role of Context
Standalone embeddings assign a single vector per word, which works well for words with one meaning. However, many words exhibit polysemy – multiple meanings depending on context (e.g., "bank" can be a financial institution, river bank, or a turn by an airplane). A single embedding averages these meanings, losing crucial nuance. The solution is contextual embeddings, which adjust a word's representation based on surrounding words. Transformers are the key to computing contextual embeddings.
Learning Standalone Embeddings from Data
The naive approach – manually collecting synonyms and antonyms – is impractical. Instead, we leverage a key insight from linguist John Firth:
"You shall know a word by the company it keeps."
Words that appear in similar contexts (i.e., the same sentences) tend to have similar meanings. For example, in the blank "The acting in the ______ was superb," plausible words include "movie," "film," "play," "musical" – all related to performances. Implausible words like "banana" would never appear there.
Co-occurrence Matrix
To operationalize Firth's idea, we define context as "appearing in the same sentence." By processing a large corpus (e.g., all of Wikipedia), we count how often every pair of words co-occurs in the same sentence. This yields a word-word co-occurrence matrix X, where Xij is the number of sentences containing both word i and word j.
Rows and columns represent all distinct words in the vocabulary (e.g., 500,000).
The matrix is symmetric: Xij=Xji.
Most entries are zero (many word pairs never co-occur), but some are large (e.g., "deep" and "learning" may co-occur thousands of times).
If two words are interchangeable (synonyms), their row vectors in X will be very similar – they co-occur with the same set of other words. Thus, the co-occurrence matrix captures contextual similarity.
The GloVe Model (Global Vectors for Word Representation)
GloVe is a popular method for learning standalone embeddings by factorizing the co-occurrence matrix. The core idea: find embeddings for each word such that their dot products (plus biases) can predict the log of the co-occurrence counts.
Define:
Xij = co-occurrence count (observed data).
wi = embedding vector for word i (learned).
w~j = context embedding vector for word j (learned; often combined with wi).
bi, bj = scalar biases (learned).
The model posits:
Taking the logarithm compresses the wide range of counts (many zeros, some large numbers), making regression well-behaved. (We add 1 to Xij to avoid log0.)
To learn the parameters, we minimize the mean squared error between predicted and actual log-co-occurrence:
This is essentially a linear regression problem with billions of data points (all word pairs). We use stochastic gradient descent to find the optimal embeddings and biases. The resulting wi vectors are the final word embeddings.
Why this works: If the embeddings faithfully reconstruct the co-occurrence pattern, they must capture the underlying contextual similarities. Words with similar rows in X will have similar embeddings.
Embedding Dimensionality
The dimension of the embedding vectors is a hyperparameter (commonly 50, 100, 200, 300). Longer vectors provide more capacity to capture complex relationships but risk overfitting. In practice, the number of parameters (vocab size × dimension) is far smaller than the number of training examples (vocab size²), so overfitting is less of a concern than in typical supervised learning.
Properties of Learned Embeddings
Semantic similarity: Similar words are close in embedding space. t-SNE visualizations show clusters like family members (brother, sister, uncle, aunt), male/female pairs, and nobility terms.
Word vector algebra: Directions capture analogies. For example:
wbrother−wman≈wsister−wwoman
The same vector shift (e.g., "male → female") applies across multiple pairs.
These relationships emerge purely from co-occurrence statistics, without any explicit supervision.
Pros and Cons of Pre-trained Embeddings (e.g., GloVe)
Advantages:
Useful when you have limited labeled data – you can leverage embeddings trained on massive generic corpora.
Capture general linguistic knowledge (e.g., basic syntax and semantics).
Disadvantages:
Not customized to domain-specific vocabulary (e.g., medical/legal jargon).
May be trained on different data distributions, causing mismatch (e.g., Wikipedia vs. song lyrics).
Cannot handle polysemy – they provide an average representation for each word.
Recommendation: Start with pre-trained embeddings if you have little data; if you have enough data, fine-tune them or train from scratch.
Using Embeddings in Keras
The standard pipeline (STIE) involves:
Standardize – lowercase, strip punctuation.
Tokenize – split into words, assign integer indices.
Index – map each token to its integer.
Encode – previously one-hot; now use an Embedding layer.
In Keras, use TextVectorization with output_mode='int' to produce integer sequences instead of one-hot vectors. Then apply an Embedding layer to map each integer to a dense vector.
Padding and Truncation
Neural networks require fixed-length inputs. Thus, after tokenization, we:
Choose a maximum sequence length (e.g., 300 for song lyrics after analyzing length distribution).
Pad shorter sequences with a special pad token (index 0) at the end.
Truncate longer sequences to the first
max_lengthtokens.
The Embedding Layer
keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim) creates a trainable lookup table of shape (vocab_size, embedding_dim). When given a batch of integer sequences, it outputs a 3D tensor of shape (batch, seq_len, embedding_dim).
To make this compatible with dense layers, we typically reduce the sequence dimension via:
GlobalAveragePooling1D: Averages all token embeddings in a sequence to produce a single vector per input.
Concatenation or summing are alternatives.
Three Approaches to Using Embeddings in Keras
1. Frozen Pre-trained Embeddings
Load GloVe vectors for the words in your vocabulary (only the top max_tokens most frequent words). Initialize the Embedding layer with these vectors and set trainable=False. This uses the pre-trained knowledge without modification.
Advantage: Fast training, good for small datasets.
Potential issue: Domain mismatch may limit performance.
2. Fine-tuned Pre-trained Embeddings
Same as above but set trainable=True. Backpropagation updates the embeddings during training, adapting them to the specific task.
Advantage: Can improve performance when you have enough data.
Risk: Overfitting if the dataset is too small.
3. Learned from Scratch
Initialize the Embedding layer randomly (or with a simple scheme) and train it end-to-end on your classification/regression task. No pre-trained vectors are used.
Advantage: Fully customized to the task at hand.
Requirement: Sufficient training data to learn meaningful vectors.
Example: Song Genre Classification
Using a dataset of ~49,000 song lyrics (hip-hop, rock, pop), a model was built with the following architecture:
TextVectorization(output_mode='int', max_tokens=5000, ...)→ integer sequences.Embedding(5000, 100, weights=[glove_matrix], trainable=False)→ frozen GloVe.GlobalAveragePooling1D()→ 100-dimensional vector.Dense(8, activation='relu')→ hidden layer.Dense(3, activation='softmax')→ genre output.
Results:
Frozen GloVe: ~63% validation accuracy.
Fine-tuned GloVe: ~69% validation accuracy.
Scratch embeddings (dim=64): ~72% validation accuracy.
With 50k examples, the model benefits from learning task-specific embeddings rather than relying on generic pre-trained vectors.
Key takeaway: Pre-trained embeddings are most valuable when data is scarce. With abundant domain-specific data, training embeddings from scratch often yields better performance.
Summary
One-hot vectors are inefficient and ignore word meaning.
Word embeddings are dense, low-dimensional vectors that capture semantic relationships through geometric proximity and direction.
The GloVe model learns embeddings by factorizing a word-word co-occurrence matrix using a simple log-linear regression, trained with stochastic gradient descent.
Pre-trained embeddings (e.g., GloVe) can speed up training and improve performance on small datasets but may need fine-tuning or replacement for larger domain-specific tasks.
In Keras, embeddings are implemented via the
Embeddinglayer, combined with padding/truncation and pooling to produce fixed-size inputs for downstream layers.

Ask anything
We've read this whole study set, so questions about it get the best answers.