The Problem with One-Hot Vectors
If the vocabulary has 10,000 words, a one-hot vector has 10,000 numbers with a single 1. It is huge and it says nothing about meaning: cat is as far from kitten as from car.
The Embedding Idea
An embedding gives each word a short list of numbers, for example 50 or 100, called a vector. The values are learned during training so that words used in similar ways get similar vectors.
Simple example: Imagine a map where each word is a point. Cat and dog sit close together, and king and queen too. Banana is far away. The embedding is that map.
The Keras Embedding Layer
python
import keras
from keras import layers
import numpy as np
emb = layers.Embedding(input_dim=1000, output_dim=8) # 1000 words, 8 numbers each
ids = np.array([[4, 25, 7]]) # three word indices
vectors = emb(ids)
print(vectors.shape) # (1, 3, 8): batch, words, embedding size
| Argument | Meaning |
input_dim | Vocabulary size |
output_dim | Length of each word vector |
mask_zero=True | Ignore padding (index 0) in later layers such as LSTM |
trainable | Set False to freeze pretrained vectors |
Learn Embeddings While Training
python
model = keras.Sequential([
keras.Input(shape=(100,)),
layers.Embedding(10000, 32),
layers.GlobalAveragePooling1D(), # average all word vectors of a sentence
layers.Dense(16, activation="relu"),
layers.Dense(1, activation="sigmoid"),
])
Pretrained Embeddings (GloVe)
With a small dataset it helps to start from vectors that were learned on billions of words, such as GloVe. You download the file, read it into a dictionary and copy the vectors into a matrix.
python
embedding_dim = 100
embeddings_index = {}
with open("glove.6B.100d.txt", encoding="utf8") as f:
for line in f:
parts = line.split()
embeddings_index[parts[0]] = np.asarray(parts[1:], dtype="float32")
vocab = vectorizer.get_vocabulary()
matrix = np.zeros((len(vocab), embedding_dim))
for i, word in enumerate(vocab):
vec = embeddings_index.get(word)
if vec is not None:
matrix[i] = vec
emb_layer = layers.Embedding(
len(vocab), embedding_dim,
embeddings_initializer=keras.initializers.Constant(matrix),
trainable=False
)
Measure Similarity
python
def cosine(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
print(cosine(embeddings_index["king"], embeddings_index["queen"])) # high
print(cosine(embeddings_index["king"], embeddings_index["banana"])) # low
Tip: Modern Transformer models create embeddings that depend on the sentence context. But the Embedding layer is still the first step of nearly all text models.
Conclusion
Embeddings turn words into meaningful vectors that the network can learn and compare. They are the foundation of modern NLP.
Quick Summary: Embedding(vocab, dim) maps word ids to learned vectors. Use pretrained vectors for small datasets.