Skip to content

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.

Applied ~12 min8 steps

What runs in CodeSplash

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

Read first

01

A word is the sum of its pieces

Read

Word2vec 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.

02

Words the text never had

Read
Word vectorsRecorded · Python and R agreeRecorded 2026-11-25 · 18 values compared
R

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

Plots

Map of the most frequent wordsWhich levels of a categorical variable does the model treat as alike?

The first two principal components of the word vectors; words close together are used in similar contexts.

View data
WordCountComponent 1Component 2
the891.1220.0021
and300.3988−0.0035
a170.1998−0.0082
in120.1578−0.0012
with110.11630.0018
rates100.0673−0.0027
after90.0699−0.0053
as80.06790.0120
it80.07750.0190
team8−0.0120−0.0049
interest70.06240.0072
match70.0052−0.0200
bank60.02030.0065
higher60.00460.0022
before5−0.0155−0.0112
for5−0.0169−0.0276
garlic50.0362−0.0126
inflation5−0.00470.0001
markets5−0.01660.0014
of5−0.01290.0152
profits5−0.01390.0032
shares50.02660.0049
striker5−0.0293−0.0069
to50.00090.0452
until5−0.00230.0014
bake4−0.04470.0044
fans4−0.0276−0.0102
investors40.0107−0.0011
league4−0.03600.0044
on40.0031−0.0117
onions4−0.0315−0.0241
sauce4−0.01880.0032
add3−0.0345−0.0223
bond30.0118−0.0241
coach3−0.08380.0173
company3−0.06440.0085
cup3−0.0446−0.0292
fell3−0.01490.0129
final3−0.04300.0056
goal3−0.02670.0093
goalkeeper3−0.02320.0051
herbs3−0.0216−0.0033
home3−0.04850.0057
its30.03570.0277
kept3−0.0379−0.0145
lemon30.00620.0034
let3−0.0152−0.0033
made3−0.03070.0087
oil3−0.02910.0157
olive3−0.0062−0.0064
penalty3−0.04500.0052
salt3−0.0176−0.0015
simmer3−0.0306−0.0060
stadium3−0.06180.0022
stock3−0.02980.0126
their30.1966−0.0076
against2−0.04790.0083
at2−0.0826−0.0050
ball2−0.0405−0.0059
bonds2−0.0413−0.0223
Nearest wordsWhich words or phrases appear most in a text column, overall or by group?
View data
Cosine similarityWordNeighbor
0.9677matchteam
0.9595matchafter
0.9496matchminutes
0.9883matchesafter
0.9870matchesrates
0.9862matchesthen
0.8767ovengolden
0.8623ovenmade
0.8104ovenwarm
0.7527ovenscaptain
0.6367ovenscut
0.6358ovensserve

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

WordRankNeighborCosine similarity
match1team0.9677
match2after0.9595
match3minutes0.9496
matches1after0.9883
matches2rates0.9870
matches3then0.9862
oven1golden0.8767
oven2made0.8623
oven3warm0.8104
ovens1captain0.7527
ovens2cut0.6367
ovens3serve0.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"))
))
Python

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

WordRankNeighborCosine similarity
match1team0.9677
match2after0.9595
match3minutes0.9496
matches1after0.9883
matches2rates0.9870
matches3then0.9862
oven1golden0.8767
oven2made0.8623
oven3warm0.8104
ovens1captain0.7527
ovens2cut0.6367
ovens3serve0.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.

03

Vector is not knowledge

Predict

Predict first

A product code like "XR7-2000" appears nowhere in the training text, but fastText gives it a vector. Can you trust its neighbors?

Yes: it has a vector, so the model knows itOnly as far as its pieces are informative: check before relying on itNo: unseen words always get random vectors
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.

Reference · LNG006 · Runs in CodeSplashfastText subword embeddingsExtends static word embeddings using character n-grams, allowing vectors for rare or previously unseen words. It is particularly useful for morphologically rich text and spelling variation, while remaining much cheaper…
04

Doc2Vec: a vector per document

Read

Paragraph 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.

05

Document vectors that run here

Read

For 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.

06

Where it stands in CodeSplash

Read
EntryIn 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
07

Check: subwords and documents

Checkpoint

Check 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.

08

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