Home / Natural Language Processing

How Words are Represented in Neural Networks

Networks never see letters. Pick a word and follow it through the pipeline: word → ID → one-hot vector → dense embedding.

Overview

The Chain of Translations

A neural network is a pile of multiplications and additions — it can only consume numbers. So every word goes through a chain of translations: word → token ID → one-hot vector → dense embedding. Each stage exists to fix a shortcoming of the previous one.

Vocabulary (10 words)

Click a word to trace its representation. Click a second word to compare embeddings.

Similarity Check

Select two words to compare their dense embeddings.

Representation Pipeline

Word
Token ID
One-Hot
Embedding

1 · The word (as humans see it)

cat

2 · Token ID (dictionary lookup)

1

3 · One-hot vector — sparse, size = vocabulary (10)

A single 1 at the word's index. No word is "closer" to any other — every pair is equally distant.

4 · Dense embedding — small, learned, meaningful (4 dims)

Each cell is a learned feature. Similar words end up with similar numbers — that's what makes embeddings powerful.

From "cat" to a Vector: Word Representation in Neural Networks

The four stages every word passes through before a network can compute with it.

Token IDs and Their Trap

The dictionary lookup ("cat" → 1, "dog" → 3) is compact, but the raw integers smuggle in a false claim: that "dog" (3) is somehow three times "cat" (1), or that words with adjacent IDs are related. The IDs are arbitrary labels, and arithmetic on labels is meaningless — a network fed raw IDs will happily learn those fake relationships.

One-Hot: Honest but Wasteful

One-hot encoding fixes the fake-ordering problem: each word becomes a vector of zeros with a single 1 at its index. Now no word is numerically "bigger" than another. The costs:

  • Size: the vector is as long as the vocabulary — 50,000 dimensions for a modest one.
  • No similarity: every pair of one-hot vectors is exactly the same distance apart. "cat" is as far from "kitten" as from "carburetor".

Dense Embeddings: Small and Meaningful

An embedding layer maps each token ID to a short vector of learned real numbers (4 dims in the demo; 300–4096 in practice). Because these values are trained rather than assigned, words used in similar contexts drift toward similar vectors — similarity becomes measurable with a dot product. This single idea underpins everything from word2vec to the input layer of GPT.

From an index to a vector

Inside a network, a word is a row of a matrix. The path from text to that row is short:

  1. The tokeniser maps the word (or subword) to an integer id.
  2. That id indexes the embedding matrix, of shape (vocabulary size × embedding dimension).
  3. The selected row is the word's vector, and it is what every subsequent layer operates on.

"cat" → id 2317 → row 2317 of a 50,000 × 768 matrix → 768 numbers

That matrix is learned. It starts as small random values and is updated by gradient descent along with everything else, so the geometry that emerges — which words end up near which — is a product of the training objective, not of anything designed.

Mathematically the lookup is equivalent to multiplying a one-hot vector by the matrix, which is why embeddings are sometimes described that way. Implementations never do it: nn.Embedding is a row lookup, because multiplying by a vector of 49,999 zeros is wasted work.

Why not one-hot all the way through

A one-hot representation has two defects that the embedding fixes.

Size. 50,000 dimensions per token, of which one is non-zero. A first layer taking that input needs 50,000 weights per unit.

No similarity. Every pair of words is exactly equidistant. "Cat" is as far from "dog" as from "bureaucracy", so nothing a model learns about one word transfers to a related one.

An embedding of 768 dimensions is 65 times smaller and places related words near each other, so evidence generalises. That combination — compact and meaningfully arranged — is what makes the representation useful.

 One-hotEmbedding
DimensionsVocabulary size100–1,024
ValuesOne 1, rest 0All non-zero
Similar wordsEquidistantNearby
LearnedNoYes
Unseen wordImpossible to representHandled by subword pieces

Static and contextual

Static embeddings (Word2Vec, GloVe, and the embedding layer of a small model) give one vector per word, fixed after training. "Bank" gets a single vector that averages the river and the financial senses into something that is neither.

Contextual embeddings are what a transformer produces at each layer: the vector for "bank" in "river bank" has absorbed information from "river" and differs from the same token in "savings bank".

The embedding table still exists in a transformer — it supplies the input to layer one. Everything after that is contextual, refined by each block. So a transformer has both: a static lookup at the bottom, and increasingly context-dependent representations above it.

A detail worth knowing: the output projection to vocabulary size is frequently tied to the embedding matrix, using the same weights transposed. It saves a large number of parameters (50,000 × 768 is 38 million) and usually improves quality slightly, on the reasoning that the input and output spaces describe the same vocabulary.

From a string to a vector, in four steps

A word becomes an index, the index becomes a static vector, and the static vector becomes a context-dependent one. Each step is run here, ending with the same word getting two different representations in two sentences.

example_01.pyNumPy
Output

Try it yourself

  1. Click "cat". Follow all four stages — note the one-hot row has a single lit cell at index 1, and the embedding is just 4 numbers.
  2. Click "dog" as the second word. The similarity panel shows a high cosine score — the demo embeddings encode that cats and dogs are both animals.
  3. Compare "cat" with "on". An animal versus a preposition: the similarity collapses. One-hot vectors could never express this difference — embeddings do it natively.

Worth remembering

Word representation is a ladder: IDs are compact but lie about order, one-hot is honest but huge and similarity-blind, and dense embeddings are small, learned, and encode meaning as geometry. Modern NLP starts at the top of that ladder.

What the geometry contains

The arrangement that emerges from training is genuinely structured, in ways that can be measured.

Neighbourhoods are semantic. The nearest vectors to "January" are the other months. The nearest to "hospital" are clinic, doctor, patient.

Directions carry relations. The offset from "man" to "woman" is roughly the offset from "king" to "queen", which is what makes the famous analogy arithmetic work. It works cleanly for a small number of well-chosen relations and is frequently overstated.

Frequency affects magnitude. Rare words often have longer vectors than common ones, which is one reason cosine similarity — which ignores length — is preferred to the dot product for comparing them.

Bias is encoded too. The vectors reproduce the statistical associations of the training corpus, including its prejudices. This is a documented and repeatedly reproduced finding, and it matters whenever embeddings feed decisions about people.

Individual dimensions are not interpretable. Directions in the space often are, and probing classifiers can find them — there is a direction that separates singular from plural, another that tracks sentiment.

Practical notes

import torch.nn as nn

emb = nn.Embedding(num_embeddings=50_000, embedding_dim=768,
                   padding_idx=0)         # keeps the pad vector at zero
x = emb(token_ids)                        # (batch, seq) -> (batch, seq, 768)

padding_idx matters: it keeps that row fixed at zero and excludes it from gradient updates, so padding contributes nothing.

Three further points that come up in real work:

The embedding table is often the largest single parameter block in a small model. 50,000 × 768 is 38 million weights, which may exceed all the transformer layers in a compact model.

Freezing pretrained embeddings is worth trying with small datasets — there is far less to overfit. Fine-tune them when you have enough data or a specialised vocabulary.

Dimension is a real trade-off. 100–300 for word vectors, 768–4,096 in transformers. Larger captures more and costs memory and compute at every layer.

Questions people ask

Is the embedding matrix the same as a one-hot multiplication? Mathematically yes, computationally no — it is implemented as a row lookup.

Are embeddings trained or downloaded? Both are used. For text, downloading pretrained is almost always better. For categorical features in your own model, trained jointly.

What dimension should I use? 300 for standalone word vectors; whatever the pretrained model uses otherwise. For categorical features, roughly the fourth root of the cardinality as a starting point.

How are unseen words handled? Subword tokenisation splits them into known pieces, so there is always something to look up.

Can I inspect what a dimension means? Not usefully. Directions in the space are more interpretable than axes, and probing is the tool for finding them.

Why tie the input and output embeddings? It saves tens of millions of parameters and typically helps slightly, since both describe the same vocabulary.

Recap in one screen

  • A word becomes an integer id, which indexes a learned embedding matrix; the selected row is its vector.
  • The lookup is equivalent to a one-hot multiplication and is implemented as indexing.
  • Embeddings are compact and place similar words nearby, so learning transfers between related words.
  • Transformers keep a static table at the input and produce contextual representations above it.
  • The geometry encodes semantics, relational directions, frequency effects and corpus bias.

Recall check

0 of 3

Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.

  1. Without scrolling back — what is the one-line takeaway from this module?

  2. What does this module say about “The Chain of Translations”?

  3. What does this module say about “Token IDs and Their Trap”?

Cheat sheet

How Words are Represented in Neural Networks

A neural network is a pile of multiplications and additions — it can only consume numbers. So every word goes through a chain of translations: word → token ID → one-hot vector → dense embedding. Each stage exists to fix a shortcoming of the previous one.

NLP · vizlearn.in/natural_language_processing/how_words_are_represented_in_neural_networks.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.