Subword vectors and document vectors: fastText and Doc2Vec
fastText builds a word's vector from its character n-grams, so unseen and misspelled words still get one. Doc2Vec learns a vector per document. See what each buys you and where each misleads.
What runs in CodeSplash
- LNG006fastText subword embeddings Runs in CodeSplash
- LNG007Paragraph Vector / Doc2Vec Explained here
- Word vectors Verified in Python and R
You will be able to
- Build a fastText word vector from its character n-grams
- Explain why a vector for an unseen word isn't evidence that it is accurate
- Describe how Doc2Vec learns a document vector and why new documents are a problem
- Choose a document-vector route that runs in CodeSplash
A word is the sum of its pieces
ReadWord2vec gives each word one vector, so "ovens" learns nothing from "oven". fastTextSubword word vectors (fastText)Each word's vector is the mean of its own vector and its character n-gram vectors, so unseen words get vectors too. adds boundary marks and splits each word into character n-grams. With n = 3, "cat" becomes <ca, cat and at>. The word's vector is the sum of its n-gram vectors, and skip-gram or CBOW trains those n-gram vectors.
In the reference program, three n-gram vectors add up to 0.4 and 0.6. Millions of possible n-grams are folded into a fixed number of hash bucketsHash buckets (n-grams)Character n-grams are hashed into a fixed number of slots; n-grams that land in the same slot share a vector., so unrelated n-grams sometimes share a row.
Words the text never had
ReadSkip-gram: 8-dimensional vectors for 107 words from 485 words of text. Closest to “match”: team (0.97).
- Words with vectors
- 107
- Words of text
- 485
- Dimensions
- 8
- Loss in the last pass
- 3.973
Plots
The first two principal components of the word vectors; words close together are used in similar contexts.
View data
| Word | Count | Component 1 | Component 2 |
|---|---|---|---|
| the | 89 | 1.122 | 0.0021 |
| and | 30 | 0.3988 | −0.0035 |
| a | 17 | 0.1998 | −0.0082 |
| in | 12 | 0.1578 | −0.0012 |
| with | 11 | 0.1163 | 0.0018 |
| rates | 10 | 0.0673 | −0.0027 |
| after | 9 | 0.0699 | −0.0053 |
| as | 8 | 0.0679 | 0.0120 |
| it | 8 | 0.0775 | 0.0190 |
| team | 8 | −0.0120 | −0.0049 |
| interest | 7 | 0.0624 | 0.0072 |
| match | 7 | 0.0052 | −0.0200 |
| bank | 6 | 0.0203 | 0.0065 |
| higher | 6 | 0.0046 | 0.0022 |
| before | 5 | −0.0155 | −0.0112 |
| for | 5 | −0.0169 | −0.0276 |
| garlic | 5 | 0.0362 | −0.0126 |
| inflation | 5 | −0.0047 | 0.0001 |
| markets | 5 | −0.0166 | 0.0014 |
| of | 5 | −0.0129 | 0.0152 |
| profits | 5 | −0.0139 | 0.0032 |
| shares | 5 | 0.0266 | 0.0049 |
| striker | 5 | −0.0293 | −0.0069 |
| to | 5 | 0.0009 | 0.0452 |
| until | 5 | −0.0023 | 0.0014 |
| bake | 4 | −0.0447 | 0.0044 |
| fans | 4 | −0.0276 | −0.0102 |
| investors | 4 | 0.0107 | −0.0011 |
| league | 4 | −0.0360 | 0.0044 |
| on | 4 | 0.0031 | −0.0117 |
| onions | 4 | −0.0315 | −0.0241 |
| sauce | 4 | −0.0188 | 0.0032 |
| add | 3 | −0.0345 | −0.0223 |
| bond | 3 | 0.0118 | −0.0241 |
| coach | 3 | −0.0838 | 0.0173 |
| company | 3 | −0.0644 | 0.0085 |
| cup | 3 | −0.0446 | −0.0292 |
| fell | 3 | −0.0149 | 0.0129 |
| final | 3 | −0.0430 | 0.0056 |
| goal | 3 | −0.0267 | 0.0093 |
| goalkeeper | 3 | −0.0232 | 0.0051 |
| herbs | 3 | −0.0216 | −0.0033 |
| home | 3 | −0.0485 | 0.0057 |
| its | 3 | 0.0357 | 0.0277 |
| kept | 3 | −0.0379 | −0.0145 |
| lemon | 3 | 0.0062 | 0.0034 |
| let | 3 | −0.0152 | −0.0033 |
| made | 3 | −0.0307 | 0.0087 |
| oil | 3 | −0.0291 | 0.0157 |
| olive | 3 | −0.0062 | −0.0064 |
| penalty | 3 | −0.0450 | 0.0052 |
| salt | 3 | −0.0176 | −0.0015 |
| simmer | 3 | −0.0306 | −0.0060 |
| stadium | 3 | −0.0618 | 0.0022 |
| stock | 3 | −0.0298 | 0.0126 |
| their | 3 | 0.1966 | −0.0076 |
| against | 2 | −0.0479 | 0.0083 |
| at | 2 | −0.0826 | −0.0050 |
| ball | 2 | −0.0405 | −0.0059 |
| bonds | 2 | −0.0413 | −0.0223 |
View data
| Cosine similarity | Word | Neighbor |
|---|---|---|
| 0.9677 | match | team |
| 0.9595 | match | after |
| 0.9496 | match | minutes |
| 0.9883 | matches | after |
| 0.9870 | matches | rates |
| 0.9862 | matches | then |
| 0.8767 | oven | golden |
| 0.8623 | oven | made |
| 0.8104 | oven | warm |
| 0.7527 | ovens | captain |
| 0.6367 | ovens | cut |
| 0.6358 | ovens | serve |
Assumptions
- Enough text — 485 words after rare words were removed; neighbors on this little text are noisy, so read them as hints.
- The window sets the kind of similarity — A window of 2 word(s) on each side; smaller windows favor words with the same role, larger ones words on the same topic.
- Coordinates are arbitrary — Compare neighbors and similarities, not single coordinates; another seed or method rotates the vectors.
Nearest words
| Word | Rank | Neighbor | Cosine similarity |
|---|---|---|---|
| match | 1 | team | 0.9677 |
| match | 2 | after | 0.9595 |
| match | 3 | minutes | 0.9496 |
| matches | 1 | after | 0.9883 |
| matches | 2 | rates | 0.9870 |
| matches | 3 | then | 0.9862 |
| oven | 1 | golden | 0.8767 |
| oven | 2 | made | 0.8623 |
| oven | 3 | warm | 0.8104 |
| ovens | 1 | captain | 0.7527 |
| ovens | 2 | cut | 0.6367 |
| ovens | 3 | serve | 0.6358 |
- 1 rows have no text (or no words) and are left out.
- Not in the vocabulary: matches, oven, ovens, zzz.
- Built from character n-grams (no vector of their own): matches, oven, ovens.
The exact R script · R R version 4.5.1 (2025-06-13)
# Word vectors
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.word_vectors 1.1.0 · spec 31f6c56e97c2e0e5
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Rows with at least one word
TEXT <- "text"
TOKENS <- "words"
LOWER <- TRUE
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = TEXT))
warnings <- list()
docs_all <- lapply(seq_len(nrow(df)), function(i) cs_lm_tokenize(df[[TEXT]][i], TOKENS, LOWER))
rows <- which(lengths(docs_all) > 0)
n_dropped <- nrow(df) - length(rows)
if (n_dropped) warnings <- c(warnings, sprintf("%d rows have no text (or no words) and are left out.", n_dropped))
if (!length(rows)) cs_error("CS_E_NO_ROWS") # no row has any words
docs <- docs_all[rows]
# %% Vocabulary and windows (rare words removed first; windows never cross rows)
MIN_COUNT <- 2
vv <- cs_wv_vocabulary(docs, MIN_COUNT, 2000)
vocab <- vv$vocab
counts <- vv$counts
if (length(vocab) < 2) cs_error("CS_E_UNDEFINED", what = "Word vectors", reason = sprintf("fewer than two words occur at least %d times", MIN_COUNT))
ids <- cs_wv_encode(docs, vocab)
WINDOW <- 2L
if (!nrow(cs_wv_pairs(ids, WINDOW))) cs_error("CS_E_UNDEFINED", what = "Word vectors", reason = "no two kept words are within the window of each other in any row")
V <- length(vocab)
DIM <- min(8L, V)
if (DIM < 8) warnings <- c(warnings, sprintf("Only %d words are kept, so the vectors have %d dimensions instead of 8.", V, V))
# %% Fit
METHOD <- "sgns"
SEED <- 42
EPOCHS <- 5
LR <- NULL
sv <- NULL; sv_share <- NULL; final_loss <- NULL
if (METHOD == "ppmi_svd") {
X <- cs_wv_cooccurrence(ids, WINDOW, V, FALSE)
if (!any(cs_wv_ppmi(X) > 0)) cs_error("CS_E_UNDEFINED", what = "Word vectors", reason = "every pointwise mutual information is zero or negative")
fit <- cs_wv_ppmi_svd(X, DIM)
vectors <- fit$vectors; sv <- fit$sv; sv_share <- fit$share
} else if (METHOD %in% c("sgns", "cbow")) {
# Subwords (cs_subword_* ↔ codesplash.text.subword): each word is its own row plus its hashed character n-grams
if (3 > 6) cs_error("CS_E_INVALID_OPTION", option = "Shortest n-gram", allowed = "at most the longest n-gram (6)", value = "3")
SW_INDEX <- cs_subword_index(vocab, 3, 6, 2000000)
fit <- cs_subword_sgns(ids, counts, SW_INDEX, DIM, WINDOW, 5, if (is.null(EPOCHS)) 20 else EPOCHS,
if (is.null(LR)) (if (METHOD == "sgns") 0.025 else 0.05) else LR, SEED, cbow = METHOD == "cbow")
SW_IN <- fit$w_in
vectors <- fit$vectors; final_loss <- fit$loss
} else {
fit <- cs_wv_glove(cs_wv_cooccurrence(ids, WINDOW, V, TRUE), DIM, if (is.null(EPOCHS)) 50 else EPOCHS, if (is.null(LR)) 0.05 else LR, SEED)
vectors <- fit$vectors; final_loss <- fit$loss
}
# %% Nearest neighbors of the looked-up words (default: the five most frequent)
QUERY <- "match, matches, oven, ovens, zzz"
asked <- strsplit(if (LOWER) tolower(QUERY) else QUERY, "[,[:space:]]+", perl = TRUE)[[1]]
asked <- unique(asked[nzchar(asked)])
queries <- head(asked[asked %in% vocab], 9)
missing <- asked[!(asked %in% vocab)]
if (length(missing)) warnings <- c(warnings, paste0("Not in the vocabulary: ", paste(missing, collapse = ", "), "."))
by_count <- order(-counts, seq_len(V), method = "radix")
if (!length(asked)) queries <- vocab[head(by_count, 5)]
K <- 3
nb_rows <- list()
values_nb <- list()
for (q in queries) {
near <- cs_wv_neighbors(vectors, match(q, vocab), K)
for (r in seq_along(near$index)) nb_rows[[length(nb_rows) + 1L]] <- list(word = q, rank = r, neighbor = vocab[near$index[r]], cosine = near$cosine[r])
if (length(near$index)) {
values_nb[[sprintf("nearest[%s]", q)]] <- vocab[near$index[1]]
values_nb[[sprintf("similarity[%s]", q)]] <- near$cosine[1]
}
}
# Words outside the vocabulary: a vector from their character n-grams that training used (skip-gram and CBOW only)
built <- character(0)
if (METHOD %in% c("sgns", "cbow")) {
for (q in head(missing, max(0L, 9L - length(queries)))) {
vec <- cs_subword_oov_vector(q, SW_INDEX, SW_IN)
if (is.null(vec)) next
near <- cs_subword_neighbors(vec, vectors, K)
for (r in seq_along(near$index)) nb_rows[[length(nb_rows) + 1L]] <- list(word = q, rank = r, neighbor = vocab[near$index[r]], cosine = near$cosine[r])
values_nb[[sprintf("nearest[%s]", q)]] <- vocab[near$index[1]]
values_nb[[sprintf("similarity[%s]", q)]] <- near$cosine[1]
built <- c(built, q)
}
if (length(built)) {
warnings <- c(warnings, paste0("Built from character n-grams (no vector of their own): ", paste(built, collapse = ", "), "."))
queries <- c(queries, built)
}
}
# %% Artifacts: one row per word
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.word_vectors/sgns_subword_oov/out-r")
art <- data.frame(word = vocab, count = as.integer(counts))
for (k in seq_len(DIM)) art[[paste0("v", k)]] <- vectors[, k]
nanoparquet::write_parquet(art, file.path(out, "vectors.parquet"))
# %% Result
LABELS <- c(ppmi_svd = "PPMI-SVD", sgns = "Skip-gram", cbow = "CBOW", glove = "GloVe")
n_tokens <- sum(lengths(ids))
values <- list(n_docs = length(rows), n_dropped = n_dropped, n_tokens = n_tokens, vocab_size = V, dim = DIM, window = WINDOW,
method = unname(LABELS[METHOD]), final_loss = final_loss, sv_share = sv_share)
if (is.null(final_loss)) values["final_loss"] <- list(NULL)
if (is.null(sv_share)) values["sv_share"] <- list(NULL)
if (!is.null(sv)) for (k in seq_len(DIM)) values[[sprintf("sv[%d]", k)]] <- sv[k]
if (METHOD %in% c("sgns", "cbow")) {
values$method <- paste(values$method, "with subwords")
values$subword_buckets <- length(SW_INDEX$used)
}
values <- c(values, values_nb)
assumptions <- list(
list(key = "enough_text", label = "Enough text", status = if (n_tokens < 10000) "warn" else "pass",
detail = paste0(sprintf("%d words after rare words were removed", n_tokens), if (n_tokens < 10000) "; neighbors on this little text are noisy, so read them as hints." else ".")),
list(key = "window_meaning", label = "The window sets the kind of similarity", status = "info",
detail = sprintf("A window of %d word(s) on each side; smaller windows favor words with the same role, larger ones words on the same topic.", WINDOW)),
list(key = "coordinates_arbitrary", label = "Coordinates are arbitrary", status = "info",
detail = "Compare neighbors and similarities, not single coordinates; another seed or method rotates the vectors.")
)
nb_cols <- list(list(key = "word", label = "Word"), list(key = "rank", label = "Rank", type = "number"),
list(key = "neighbor", label = "Neighbor"), list(key = "cosine", label = "Cosine similarity", type = "number"))
top <- head(by_count, 60)
xy <- cs_wv_map_2d(vectors)
charts <- list(cs_chart("map", "embedding-map", "Map of the most frequent words", list(
x = cs_col("Component 1", xy[top, 1], "numeric"),
y = cs_col("Component 2", xy[top, 2], "numeric"),
label = cs_col("Word", vocab[top], "categorical"),
size = cs_col("Count", counts[top], "numeric")
), note = "The first two principal components of the word vectors; words close together are used in similar contexts."))
if (length(nb_rows)) {
charts[[2]] <- cs_chart("neighbors", "ngram-bars", "Nearest words", list(
term = cs_col("Neighbor", vapply(nb_rows, `[[`, "", "neighbor"), "categorical"),
count = cs_col("Cosine similarity", vapply(nb_rows, `[[`, 0, "cosine"), "numeric"),
group = cs_col("Word", vapply(nb_rows, `[[`, "", "word"), "categorical", queries)
))
}
summary <- sprintf("%s: %d-dimensional vectors for %d words from %d words of text.", LABELS[[METHOD]], DIM, V, n_tokens)
if (length(queries) && !is.null(values[[sprintf("nearest[%s]", queries[1])]])) {
summary <- paste0(summary, sprintf(" Closest to “%s”: %s (%.2f).", queries[1], values[[sprintf("nearest[%s]", queries[1])]], values[[sprintf("similarity[%s]", queries[1])]]))
}
stats <- list(list(key = "vocab_size", label = "Words with vectors", value = V), list(key = "n_tokens", label = "Words of text", value = n_tokens),
list(key = "dim", label = "Dimensions", value = DIM))
if (!is.null(sv_share)) stats[[length(stats) + 1L]] <- list(key = "sv_share", label = "PPMI kept by these dimensions", value = sv_share)
if (!is.null(final_loss)) stats[[length(stats) + 1L]] <- list(key = "final_loss", label = "Loss in the last pass", value = final_loss)
cs_publish(list(
title = "Word vectors",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = stats,
tables = list(list(key = "neighbors", title = "Nearest words", columns = nb_cols, rows = nb_rows)),
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "vectors", path = file.path(out, "vectors.parquet"), format = "parquet"))
))
Skip-gram: 8-dimensional vectors for 107 words from 485 words of text. Closest to “match”: team (0.97).
- Words with vectors
- 107
- Words of text
- 485
- Dimensions
- 8
- Loss in the last pass
- 3.973
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough text — 485 words after rare words were removed; neighbors on this little text are noisy, so read them as hints.
- The window sets the kind of similarity — A window of 2 word(s) on each side; smaller windows favor words with the same role, larger ones words on the same topic.
- Coordinates are arbitrary — Compare neighbors and similarities, not single coordinates; another seed or method rotates the vectors.
Nearest words
| Word | Rank | Neighbor | Cosine similarity |
|---|---|---|---|
| match | 1 | team | 0.9677 |
| match | 2 | after | 0.9595 |
| match | 3 | minutes | 0.9496 |
| matches | 1 | after | 0.9883 |
| matches | 2 | rates | 0.9870 |
| matches | 3 | then | 0.9862 |
| oven | 1 | golden | 0.8767 |
| oven | 2 | made | 0.8623 |
| oven | 3 | warm | 0.8104 |
| ovens | 1 | captain | 0.7527 |
| ovens | 2 | cut | 0.6367 |
| ovens | 3 | serve | 0.6358 |
- 1 rows have no text (or no words) and are left out.
- Not in the vocabulary: matches, oven, ovens, zzz.
- Built from character n-grams (no vector of their own): matches, oven, ovens.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Word vectors
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.word_vectors 1.1.0 · spec 31f6c56e97c2e0e5
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import re
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.text import ngram_lm as lm
from codesplash.text import word_vectors as wv
# %% Rows with at least one word
TEXT = "text"
TOKENS = "words"
LOWER = True
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT])
warnings = []
docs_all = [lm.tokenize(t, TOKENS, LOWER) for t in df[TEXT]]
rows = [i for i, d in enumerate(docs_all) if len(d) > 0]
n_dropped = len(df) - len(rows)
if n_dropped:
warnings.append(f"{n_dropped} rows have no text (or no words) and are left out.")
if not rows:
cs.cs_error("CS_E_NO_ROWS") # no row has any words
docs = [docs_all[i] for i in rows]
# %% Vocabulary and windows (rare words removed first; windows never cross rows)
MIN_COUNT = 2
vocab, counts = wv.vocabulary(docs, MIN_COUNT, 2000)
if len(vocab) < 2:
cs.cs_error("CS_E_UNDEFINED", what="Word vectors", reason=f"fewer than two words occur at least {MIN_COUNT} times")
ids = wv.encode(docs, vocab)
WINDOW = 2
if not wv.pairs(ids, WINDOW):
cs.cs_error("CS_E_UNDEFINED", what="Word vectors", reason="no two kept words are within the window of each other in any row")
V = len(vocab)
DIM = min(8, V)
if DIM < 8:
warnings.append(f"Only {V} words are kept, so the vectors have {V} dimensions instead of 8.")
# %% Fit
METHOD = "sgns"
SEED = 42
EPOCHS = 5
LR = None
sv, sv_share, final_loss = None, None, None
if METHOD == "ppmi_svd":
X = wv.cooccurrence(ids, WINDOW, V, False)
if not np.any(wv.ppmi(X) > 0):
cs.cs_error("CS_E_UNDEFINED", what="Word vectors", reason="every pointwise mutual information is zero or negative")
vectors, sv, sv_share = wv.ppmi_svd(X, DIM)
elif METHOD in ("sgns", "cbow"):
# Subwords (codesplash.text.subword ↔ cs_subword_*): each word is its own row plus its hashed character n-grams
from codesplash.text import subword as sw
if 3 > 6:
cs.cs_error("CS_E_INVALID_OPTION", option="Shortest n-gram", allowed="at most the longest n-gram (6)", value="3")
SW_INDEX = sw.Index(vocab, 3, 6, 2000000)
vectors, SW_IN, final_loss = sw.sgns(ids, counts, SW_INDEX, DIM, WINDOW, 5, EPOCHS if EPOCHS is not None else 20,
LR if LR is not None else (0.025 if METHOD == "sgns" else 0.05), SEED, cbow=METHOD == "cbow")
else:
vectors, final_loss = wv.glove(wv.cooccurrence(ids, WINDOW, V, True), DIM, EPOCHS if EPOCHS is not None else 50,
LR if LR is not None else 0.05, SEED)
# %% Nearest neighbors of the looked-up words (default: the five most frequent)
QUERY = "match, matches, oven, ovens, zzz"
asked = [w for w in re.split(r"[,\s]+", QUERY.lower() if LOWER else QUERY) if w]
index = {w: i for i, w in enumerate(vocab)}
queries = [w for w in dict.fromkeys(asked) if w in index][:9]
missing = [w for w in dict.fromkeys(asked) if w not in index]
if missing:
warnings.append("Not in the vocabulary: " + ", ".join(missing) + ".")
if not asked:
queries = [vocab[i] for i in sorted(range(V), key=lambda i: (-counts[i], i))[:5]]
K = 3
nb_rows = []
values_nb = {}
for q in queries:
near = wv.neighbors(vectors, vocab, index[q], K)
for r, (i, c) in enumerate(near, start=1):
nb_rows.append({"word": q, "rank": r, "neighbor": vocab[i], "cosine": c})
if near:
values_nb[f"nearest[{q}]"] = vocab[near[0][0]]
values_nb[f"similarity[{q}]"] = near[0][1]
# Words outside the vocabulary: a vector from their character n-grams that training used (skip-gram and CBOW only)
built = []
if METHOD in ("sgns", "cbow"):
for q in missing[: max(0, 9 - len(queries))]:
vec = sw.oov_vector(q, SW_INDEX, SW_IN)
if vec is None:
continue
near = sw.neighbors_of(vec, vectors, K)
for r, (i, c) in enumerate(near, start=1):
nb_rows.append({"word": q, "rank": r, "neighbor": vocab[i], "cosine": c})
values_nb[f"nearest[{q}]"] = vocab[near[0][0]]
values_nb[f"similarity[{q}]"] = near[0][1]
built.append(q)
if built:
warnings.append("Built from character n-grams (no vector of their own): " + ", ".join(built) + ".")
queries = queries + built
# %% Artifacts: one row per word
out = csml.out_dir("target/academy-parity/run-8142/discover.word_vectors/sgns_subword_oov/out-python")
art = pd.DataFrame({"word": vocab, "count": counts.astype(int)})
for k in range(DIM):
art[f"v{k + 1}"] = vectors[:, k]
art.to_parquet(os.path.join(out, "vectors.parquet"), index=False)
# %% Result
LABELS = {"ppmi_svd": "PPMI-SVD", "sgns": "Skip-gram", "cbow": "CBOW", "glove": "GloVe"}
n_tokens = int(sum(len(d) for d in ids))
values = {
"n_docs": len(rows), "n_dropped": n_dropped, "n_tokens": n_tokens, "vocab_size": V, "dim": DIM, "window": WINDOW,
"method": LABELS[METHOD], "final_loss": final_loss, "sv_share": sv_share,
}
if sv is not None:
for k in range(DIM):
values[f"sv[{k + 1}]"] = float(sv[k])
if METHOD in ("sgns", "cbow"):
values["method"] += " with subwords"
values["subword_buckets"] = len(SW_INDEX.used)
values.update(values_nb)
assumptions = [
{"key": "enough_text", "label": "Enough text", "status": "warn" if n_tokens < 10000 else "pass",
"detail": f"{n_tokens} words after rare words were removed" + ("; neighbors on this little text are noisy, so read them as hints." if n_tokens < 10000 else ".")},
{"key": "window_meaning", "label": "The window sets the kind of similarity", "status": "info",
"detail": f"A window of {WINDOW} word(s) on each side; smaller windows favor words with the same role, larger ones words on the same topic."},
{"key": "coordinates_arbitrary", "label": "Coordinates are arbitrary", "status": "info",
"detail": "Compare neighbors and similarities, not single coordinates; another seed or method rotates the vectors."},
]
nb_cols = [{"key": "word", "label": "Word"}, {"key": "rank", "label": "Rank", "type": "number"},
{"key": "neighbor", "label": "Neighbor"}, {"key": "cosine", "label": "Cosine similarity", "type": "number"}]
top = sorted(range(V), key=lambda i: (-counts[i], i))[:60]
xy = wv.map_2d(vectors)
charts = [cs.chart("map", "embedding-map", "Map of the most frequent words", {
"x": cs.col("Component 1", [float(xy[i, 0]) for i in top], "numeric"),
"y": cs.col("Component 2", [float(xy[i, 1]) for i in top], "numeric"),
"label": cs.col("Word", [vocab[i] for i in top], "categorical"),
"size": cs.col("Count", [float(counts[i]) for i in top], "numeric"),
}, note="The first two principal components of the word vectors; words close together are used in similar contexts.")]
if nb_rows:
charts.append(cs.chart("neighbors", "ngram-bars", "Nearest words", {
"term": cs.col("Neighbor", [r["neighbor"] for r in nb_rows], "categorical"),
"count": cs.col("Cosine similarity", [r["cosine"] for r in nb_rows], "numeric"),
"group": cs.col("Word", [r["word"] for r in nb_rows], "categorical", queries),
}))
summary = f"{LABELS[METHOD]}: {DIM}-dimensional vectors for {V} words from {n_tokens} words of text."
if queries and f"nearest[{queries[0]}]" in values:
summary += f" Closest to “{queries[0]}”: {values[f'nearest[{queries[0]}]']} ({values[f'similarity[{queries[0]}]']:.2f})."
stats = [{"key": "vocab_size", "label": "Words with vectors", "value": V}, {"key": "n_tokens", "label": "Words of text", "value": n_tokens},
{"key": "dim", "label": "Dimensions", "value": DIM}]
if sv_share is not None:
stats.append({"key": "sv_share", "label": "PPMI kept by these dimensions", "value": sv_share})
if final_loss is not None:
stats.append({"key": "final_loss", "label": "Loss in the last pass", "value": final_loss})
cs.publish({
"title": "Word vectors",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": stats,
"tables": [{"key": "neighbors", "title": "Nearest words", "columns": nb_cols, "rows": nb_rows}],
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "vectors", "path": os.path.join(out, "vectors.parquet"), "format": "parquet"}],
})
Here Subwords (fastText) is on, and the looked-up words "matches" and "oven" never occur in the text. They still get vectors, built from n-grams that other words share. The nearest word to "matches" is "after", which is also a close neighbor of "match": the shared pieces carried real information.
The nearest word to "oven" is "golden" at cosine 0.88. That is spelling overlap, not meaning. The lesson Pretrained text models, in Generative models, uses the same run.
Vector is not knowledge
PredictPredict first
A product code like "XR7-2000" appears nowhere in the training text, but fastText gives it a vector. Can you trust its neighbors?
Reveal
Only as far as its pieces are informative. Morphology ("-ing", "-s", shared stems) transfers well; codes, names and foreign words often borrow meaning from unrelated words that happen to share letters.
Doc2Vec: a vector per document
ReadParagraph VectorParagraph Vector (Doc2Vec)Learns one vector per training document alongside word vectors; a new document's vector must be fitted by extra gradient steps. (Doc2Vec) gives every training document its own vector and treats it like one more context word. In the PV-DM variant, the document vector and the nearby word vectors together predict the next word. In the reference program, a document vector joined with one word vector predicts the target word with loss 0.598.
The catch is new documents. Their vectors aren't in the model, so each must be fitted by gradient steps with the word vectors frozen. That inference changes with the seed and step count, so the same document can land in different places.
Document vectors that run here
ReadFor a vector per document, CodeSplash offers routes that don't need fitting per new document:
- Sentence embeddings from a pretrained encoder (MiniLM, E5 and others), used by Semantic search, BERTopic and Text encoder: the same text always gets the same vector.
- TF-IDF with a truncated SVD (latent semantic analysis), the count-based route inside BERTopic.
Doc2Vec itself is explained here only. Subword vectors run in Word vectors with skip-gram or CBOW, in Python and R.
Where it stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| fastText subword vectors (LNG006) | Runs in CodeSplash: Word vectors, Subwords (fastText) with skip-gram or CBOW |
| Paragraph Vector / Doc2Vec (LNG007) | Explained here; use sentence embeddings or TF-IDF + SVD for document vectors |
Check: subwords and documents
CheckpointCheck yourself
How does fastText build the vector of a word?
Show the answer
Answer: b
Splitting into n-grams with boundary marks lets words share pieces, so related forms like "match" and "matches" share most of their vector.
Check yourself
A misspelled word gets a vector whose nearest neighbor looks unrelated. What is the most likely reason?
Show the answer
Answer: b
Subword vectors transfer what spelling can carry and no more. Check unseen words' neighbors before trusting them.
Check yourself
In Doc2Vec's PV-DM training, what plays the role of an extra context word?
Show the answer
Answer: a
Each training document has a learned vector that joins the word vectors in predicting the next word, so it absorbs what the words around it don't explain.
Check yourself
Why can Doc2Vec give the same new document different vectors on two runs?
Show the answer
Answer: b
New documents need an optimization of their own. Pretrained sentence encoders compute a vector in one fixed pass, so the same text always gets the same vector.
Recap
Recap- fastText sums character n-gram vectors, folded into hash buckets, so unseen words get vectors; spelling is not meaning.
- Doc2Vec learns a vector per training document; new documents need unstable fitting.
- In CodeSplash: subword vectors in Word vectors; document vectors from sentence encoders or TF-IDF + SVD.
Concepts in this lesson