Words known by the company they keep: word vectors
Learn a vector for every frequent word from the words around it, read nearest neighbors honestly, and see why counts beat word2vec on a small collection.
What runs in CodeSplash
- Word vectors Verified in Python and R
You will be able to
- Explain how window counts become word vectors (PPMI-SVD, skip-gram, CBOW, GloVe)
- Read nearest neighbors and their cosine similarity
- Choose a method and window for the amount of text you have
Read first
Context instead of definitions
ReadNobody tells the model what "salt" means. It only sees which words appear near it, and words used in similar places end up with similar word vectorsWord vectorA list of numbers per word, learned from the words around it, so words used in similar contexts get similar vectors.. A topic model asks which words share a document. Word vectors ask which words share a small windowContext windowHow many words on each side count as a word's context; windows never cross from one row to the next.: the few words on either side.
The simplest route counts how often each pair of words shares a window. It then turns the counts into PPMIPPMIlog of how much more often two words share a window than chance predicts, with negative values set to 0.: how much more often the pair co-occurs than chance would predict, with negative values set to zero. An SVD of that matrix keeps the strongest patterns as a short vector per word.
Neighbors in a small collection
ReadPPMI-SVD: 12-dimensional vectors for 291 words from 649 words of text. Closest to “goal”: late (0.95).
- Words with vectors
- 291
- Words of text
- 649
- Dimensions
- 12
- PPMI kept by these dimensions
- 0.2718
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 | 71 | −0.2709 | 0.1388 |
| and | 30 | −0.4966 | −0.4191 |
| The | 18 | 0.4750 | 0.7618 |
| a | 15 | 0.0943 | 0.6886 |
| in | 12 | −0.2399 | 0.1948 |
| with | 11 | −0.6388 | −0.2496 |
| rates | 10 | 0.9009 | −0.8225 |
| after | 8 | 0.6007 | 0.9680 |
| as | 8 | 0.9707 | −0.5396 |
| it | 8 | −0.4783 | −0.3660 |
| team | 8 | −0.1322 | 0.3924 |
| interest | 7 | 0.9543 | −0.7169 |
| match | 7 | −0.1708 | 0.5050 |
| bank | 6 | 0.6680 | −0.2034 |
| higher | 6 | 0.6176 | −0.3189 |
| before | 5 | −0.3258 | −0.0558 |
| for | 5 | −0.2154 | −0.3017 |
| garlic | 5 | −0.5751 | −0.3922 |
| of | 5 | 0.2438 | 0.2196 |
| striker | 5 | −0.0633 | 0.5469 |
| to | 5 | 0.4310 | −0.1089 |
| until | 5 | −0.4996 | −0.4736 |
| markets | 4 | 0.4842 | −0.0580 |
| on | 4 | 0.3859 | −0.5947 |
| onions | 4 | −0.4141 | −0.1548 |
| profits | 4 | 0.7702 | 0.2888 |
| sauce | 4 | −0.4311 | −0.2953 |
| shares | 4 | 0.6650 | 0.1562 |
| coach | 3 | −0.0717 | 0.3833 |
| company | 3 | 0.6011 | 0.4427 |
| cup | 3 | −0.0847 | 0.1286 |
| fans | 3 | −0.1717 | 0.0430 |
| fell | 3 | 0.5970 | −0.5422 |
| final | 3 | −0.2284 | 0.2946 |
| goal | 3 | −0.1986 | 0.2439 |
| goalkeeper | 3 | 0.1030 | 0.3474 |
| herbs | 3 | −0.4529 | −0.3802 |
| home | 3 | −0.1261 | −0.0652 |
| inflation | 3 | 0.4172 | 0.0464 |
| its | 3 | 0.6107 | 0.3710 |
| kept | 3 | −0.1483 | 0.3439 |
| league | 3 | −0.1034 | 0.2426 |
| lemon | 3 | −0.5333 | −0.4648 |
| made | 3 | 0.2354 | −0.0745 |
| oil | 3 | −0.4484 | −0.3211 |
| olive | 3 | −0.4443 | −0.2998 |
| penalty | 3 | −0.1348 | 0.4825 |
| salt | 3 | −0.2900 | −0.0118 |
| stadium | 3 | −0.0931 | 0.0761 |
| their | 3 | −0.2753 | 0.1270 |
| A | 2 | −0.0655 | 0.4013 |
| Add | 2 | −0.0696 | −0.1078 |
| Bake | 2 | −0.2500 | −0.1825 |
| Bond | 2 | 0.1578 | 0.2367 |
| Inflation | 2 | −0.1612 | −0.0518 |
| Investors | 2 | 0.3871 | 0.0882 |
| Roast | 2 | −0.2772 | −0.0649 |
| against | 2 | −0.1879 | 0.3054 |
| at | 2 | 0.0368 | 0.0482 |
| bake | 2 | −0.3400 | −0.2647 |
View data
| Cosine similarity | Word | Neighbor |
|---|---|---|
| 0.9498 | goal | late |
| 0.9261 | goal | scored |
| 0.9251 | goal | winning |
| 0.8804 | goal | awarded |
| 0.8637 | goal | striker |
| 0.9419 | rates | income |
| 0.9257 | rates | lending |
| 0.9090 | rates | welcomed |
| 0.8948 | rates | peaked |
| 0.8622 | rates | rising |
| 0.9545 | salt | pepper |
| 0.9244 | salt | pinch |
| 0.9018 | salt | add |
| 0.8908 | salt | or |
| 0.8545 | salt | little |
Assumptions
- Enough text — 649 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 3 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 |
|---|---|---|---|
| goal | 1 | late | 0.9498 |
| goal | 2 | scored | 0.9261 |
| goal | 3 | winning | 0.9251 |
| goal | 4 | awarded | 0.8804 |
| goal | 5 | striker | 0.8637 |
| rates | 1 | income | 0.9419 |
| rates | 2 | lending | 0.9257 |
| rates | 3 | welcomed | 0.9090 |
| rates | 4 | peaked | 0.8948 |
| rates | 5 | rising | 0.8622 |
| salt | 1 | pepper | 0.9545 |
| salt | 2 | pinch | 0.9244 |
| salt | 3 | add | 0.9018 |
| salt | 4 | or | 0.8908 |
| salt | 5 | little | 0.8545 |
- 1 rows have no text (or no words) and are left out.
- Not in the vocabulary: nonexistent.
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 1061cc787b009257
# 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 <- "whitespace"
LOWER <- FALSE
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 <- 1
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 <- 3L
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(12L, V)
if (DIM < 12) warnings <- c(warnings, sprintf("Only %d words are kept, so the vectors have %d dimensions instead of 12.", V, V))
# %% Fit
METHOD <- "ppmi_svd"
SEED <- 42
EPOCHS <- NULL
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")) {
fit <- cs_wv_sgns(ids, counts, 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")
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 <- "goal,rates,salt,nonexistent"
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 <- 5
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]
}
}
# %% Artifacts: one row per word
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.word_vectors/ppmi_corpus_whitespace/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]
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"))
))
PPMI-SVD: 12-dimensional vectors for 291 words from 649 words of text. Closest to “goal”: late (0.95).
- Words with vectors
- 291
- Words of text
- 649
- Dimensions
- 12
- PPMI kept by these dimensions
- 0.2718
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough text — 649 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 3 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 |
|---|---|---|---|
| goal | 1 | late | 0.9498 |
| goal | 2 | scored | 0.9261 |
| goal | 3 | winning | 0.9251 |
| goal | 4 | awarded | 0.8804 |
| goal | 5 | striker | 0.8637 |
| rates | 1 | income | 0.9419 |
| rates | 2 | lending | 0.9257 |
| rates | 3 | welcomed | 0.9090 |
| rates | 4 | peaked | 0.8948 |
| rates | 5 | rising | 0.8622 |
| salt | 1 | pepper | 0.9545 |
| salt | 2 | pinch | 0.9244 |
| salt | 3 | add | 0.9018 |
| salt | 4 | or | 0.8908 |
| salt | 5 | little | 0.8545 |
- 1 rows have no text (or no words) and are left out.
- Not in the vocabulary: nonexistent.
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 1061cc787b009257
# 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 = "whitespace"
LOWER = False
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 = 1
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 = 3
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(12, V)
if DIM < 12:
warnings.append(f"Only {V} words are kept, so the vectors have {V} dimensions instead of 12.")
# %% Fit
METHOD = "ppmi_svd"
SEED = 42
EPOCHS = None
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"):
vectors, final_loss = wv.sgns(ids, counts, 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 = "goal,rates,salt,nonexistent"
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 = 5
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]
# %% Artifacts: one row per word
out = csml.out_dir("target/academy-parity/run-8142/discover.word_vectors/ppmi_corpus_whitespace/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])
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"}],
})
Sixty sentences give 649 words and 291 vocabulary entries. Even so, the nearest wordNearest wordThe vocabulary word whose vector has the highest cosine similarity with the looked-up word. to "salt" is "pepper", with cosine similarityCosine similarityThe cosine of the angle between two vectors: 1 for the same direction, 0 for unrelated, −1 for opposite. 0.95. "rates" sits next to "income". "nonexistent" was not in the text, and the card says so rather than guessing.
View data
| bigram | count | rating |
|---|---|---|
| late delivery | 62 | 1–2 stars |
| refund | 50 | 1–2 stars |
| customer service | 45 | 1–2 stars |
| broken | 39 | 1–2 stars |
| never arrived | 33 | 1–2 stars |
| waste | 25 | 1–2 stars |
| wrong size | 25 | 1–2 stars |
| poor quality | 24 | 1–2 stars |
| support | 18 | 1–2 stars |
| return | 18 | 1–2 stars |
| great quality | 74 | 4–5 stars |
| fast shipping | 60 | 4–5 stars |
| love | 52 | 4–5 stars |
| fits perfectly | 38 | 4–5 stars |
| easy | 35 | 4–5 stars |
| recommend | 33 | 4–5 stars |
| comfortable | 31 | 4–5 stars |
| good value | 26 | 4–5 stars |
| gift | 16 | 4–5 stars |
| soft | 17 | 4–5 stars |
On this little text, many neighbors are words that merely happen to share a sentence. The card warns that neighbors from fewer than about 10,000 words are hints. Read the whole list and check a few rows before trusting a neighbor.
Check yourself
In a collection of support tickets, "refund" and "cancel" are nearest neighbors. What does that show?
Show the answer
Answer: b
Word vectors capture how words are used in this text. Similar contexts can come from synonyms, opposites ("increase", "decrease") or words that simply co-occur.
Counts or prediction
Readword2vec's skip-gram and CBOWSkip-gram with negative samplingword2vec: each word's vector is trained to predict nearby words against randomly drawn noise words (CBOW predicts the middle word). predict nearby words, contrasting each real pair with randomly drawn noise words. GloVeGloVeWord vectors fitted so their dot products match the log of distance-weighted co-occurrence counts. fits vectors to the logarithm of the co-occurrence counts. Both need much more text than PPMI-SVD, as CBOW on the same sixty sentences shows:
CBOW: 8-dimensional vectors for 270 words from 648 words of text. Closest to “match”: after (1.00).
- Words with vectors
- 270
- Words of text
- 648
- Dimensions
- 8
- Loss in the last pass
- 2.800
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 | 7.631 | 0.3211 |
| and | 30 | 5.641 | −0.0064 |
| a | 17 | 4.538 | −0.1960 |
| in | 12 | 3.046 | 0.0530 |
| with | 11 | 2.863 | 0.0244 |
| rates | 10 | 2.680 | −0.1275 |
| after | 9 | 2.031 | 0.0120 |
| as | 8 | 2.572 | −0.1143 |
| it | 8 | 2.346 | 0.0094 |
| team | 8 | 0.6123 | 0.1760 |
| interest | 7 | 2.257 | −0.1051 |
| match | 7 | 1.056 | 0.1350 |
| bank | 6 | 0.9175 | −0.1125 |
| higher | 6 | 1.185 | 0.0182 |
| before | 5 | 1.720 | 0.0652 |
| for | 5 | 1.913 | −0.0277 |
| garlic | 5 | 1.199 | −0.0642 |
| inflation | 5 | 1.112 | −0.0493 |
| markets | 5 | 1.152 | −0.0881 |
| of | 5 | 1.338 | −0.0311 |
| profits | 5 | 1.319 | −0.0430 |
| shares | 5 | 0.9585 | −0.0640 |
| striker | 5 | 0.0023 | 0.0512 |
| to | 5 | 1.195 | 0.0152 |
| until | 5 | 0.7441 | 0.0215 |
| bake | 4 | 0.1544 | 0.0033 |
| fans | 4 | 0.3418 | −0.0032 |
| investors | 4 | 1.004 | 0.0078 |
| league | 4 | −0.0743 | 0.0418 |
| on | 4 | 1.483 | −0.0624 |
| onions | 4 | 0.5878 | 0.0254 |
| sauce | 4 | 0.3542 | 0.0215 |
| add | 3 | −0.1286 | 0.0663 |
| bond | 3 | 0.3142 | −0.0334 |
| coach | 3 | −0.5344 | 0.1168 |
| company | 3 | 0.1664 | −0.0003 |
| cup | 3 | −0.0468 | 0.0408 |
| fell | 3 | 0.6125 | −0.0600 |
| final | 3 | 0.1339 | 0.0418 |
| goal | 3 | −0.3707 | −0.0362 |
| goalkeeper | 3 | 0.1888 | −0.0487 |
| herbs | 3 | 0.0631 | −0.0251 |
| home | 3 | 0.0987 | −0.0294 |
| its | 3 | 0.7539 | −0.0513 |
| kept | 3 | 0.7914 | 0.0414 |
| lemon | 3 | 0.2293 | −0.0675 |
| let | 3 | 0.1846 | −0.0117 |
| made | 3 | 0.7842 | −0.0776 |
| oil | 3 | 0.4157 | −0.0220 |
| olive | 3 | 0.6152 | −0.0537 |
| penalty | 3 | −0.3898 | 0.0505 |
| salt | 3 | 0.3861 | −0.0206 |
| simmer | 3 | −0.1166 | 0.0323 |
| stadium | 3 | 0.1132 | 0.0245 |
| stock | 3 | 0.1609 | 0.0022 |
| their | 3 | 0.4019 | −0.0695 |
| against | 2 | 0.1990 | 0.0518 |
| at | 2 | −0.7060 | 0.0087 |
| ball | 2 | −0.4296 | 0.0990 |
| bonds | 2 | 0.4880 | −0.0533 |
View data
| Cosine similarity | Word | Neighbor |
|---|---|---|
| 0.9969 | match | after |
| 0.9968 | match | kept |
| 0.9962 | match | into |
| 0.9986 | bank | as |
| 0.9986 | bank | their |
| 0.9985 | bank | interest |
Assumptions
- Enough text — 648 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 3 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 | after | 0.9969 |
| match | 2 | kept | 0.9968 |
| match | 3 | into | 0.9962 |
| bank | 1 | as | 0.9986 |
| bank | 2 | their | 0.9986 |
| bank | 3 | interest | 0.9985 |
- 1 rows have no text (or no words) and are left out.
- Not in the vocabulary: oven.
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 de1486f401e3cd15
# 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 <- 1
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 <- 3L
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 <- "cbow"
SEED <- 42
EPOCHS <- 15
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")) {
fit <- cs_wv_sgns(ids, counts, 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")
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, bank, oven"
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]
}
}
# %% Artifacts: one row per word
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.word_vectors/cbow_corpus_queries/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]
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"))
))
CBOW: 8-dimensional vectors for 270 words from 648 words of text. Closest to “match”: after (1.00).
- Words with vectors
- 270
- Words of text
- 648
- Dimensions
- 8
- Loss in the last pass
- 2.800
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough text — 648 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 3 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 | after | 0.9969 |
| match | 2 | kept | 0.9968 |
| match | 3 | into | 0.9962 |
| bank | 1 | as | 0.9986 |
| bank | 2 | their | 0.9986 |
| bank | 3 | interest | 0.9985 |
- 1 rows have no text (or no words) and are left out.
- Not in the vocabulary: oven.
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 de1486f401e3cd15
# 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 = 1
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 = 3
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 = "cbow"
SEED = 42
EPOCHS = 15
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"):
vectors, final_loss = wv.sgns(ids, counts, 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, bank, oven"
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]
# %% Artifacts: one row per word
out = csml.out_dir("target/academy-parity/run-8142/discover.word_vectors/cbow_corpus_queries/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])
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 "bank" lands next to "as", with similarity 0.999. When almost every pair of words is that similar, the vectors haven't learned anything yet. On a few thousand words, use PPMI-SVD; switch to skip-gram or GloVe once you have hundreds of thousands of words.
Check yourself
You have 2,000 short product reviews (about 30,000 words). Which setting is the safer start?
Show the answer
Answer: a
PPMI-SVD has no random start and no training schedule, and it does well on small collections. Large dimensions and few passes waste a small corpus.
Coordinates are arbitrary, ratios are not
ReadPPMI-SVD: 10-dimensional vectors for 84 words from 1989 words of text. Closest to “small”: people (0.82).
- Words with vectors
- 84
- Words of text
- 1,989
- Dimensions
- 10
- PPMI kept by these dimensions
- 0.8266
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 |
|---|---|---|---|
| small | 38 | 0.0052 | 0.1561 |
| sugar | 37 | 0.0857 | 0.1132 |
| today | 35 | −0.0279 | −0.0814 |
| new | 32 | 0.1421 | 0.0744 |
| people | 32 | 0.0834 | −0.0855 |
| astronaut | 31 | 0.3368 | −0.1716 |
| said | 31 | −0.1041 | −0.0828 |
| again | 30 | −0.0947 | 0.0420 |
| dividend | 30 | −0.1527 | 0.9911 |
| late | 30 | −0.1228 | 0.1418 |
| early | 29 | 0.1906 | 0.0611 |
| stadium | 29 | 0.8191 | −0.3674 |
| big | 28 | −0.0644 | 0.2080 |
| galaxy | 28 | 0.2859 | −0.1354 |
| knead | 28 | 0.1085 | 0.1121 |
| orbit | 28 | 0.2645 | −0.1396 |
| pastry | 28 | 0.0583 | 0.0910 |
| pruning | 28 | −0.7696 | −0.6215 |
| week | 28 | −0.1312 | 0.1371 |
| clouds | 27 | −0.3592 | 0.0622 |
| investors | 27 | −0.1229 | 0.8948 |
| rates | 27 | −0.1373 | 0.9100 |
| coach | 26 | 0.7984 | −0.3907 |
| compost | 26 | −0.6854 | −0.5783 |
| crust | 26 | 0.1042 | 0.1657 |
| inflation | 26 | −0.1022 | 0.9529 |
| loaf | 26 | 0.0328 | −0.0117 |
| planet | 26 | 0.2762 | −0.1198 |
| probe | 26 | 0.2659 | −0.1270 |
| seeds | 26 | −0.8625 | −0.6852 |
| sunshine | 26 | −0.4189 | −0.0258 |
| match | 25 | 0.8432 | −0.3826 |
| midfield | 25 | 0.8666 | −0.3720 |
| oven | 25 | 0.1463 | 0.1501 |
| recipe | 25 | 0.0845 | 0.2387 |
| yields | 25 | −0.1273 | 1.027 |
| bond | 24 | −0.0906 | 0.8768 |
| good | 24 | 0.0901 | −0.1243 |
| mulch | 24 | −0.8669 | −0.6414 |
| hedge | 23 | −0.7133 | −0.5977 |
| mission | 23 | 0.3357 | −0.1648 |
| really | 23 | 0.2796 | −0.2216 |
| shares | 23 | −0.1357 | 0.9194 |
| storm | 23 | −0.3565 | 0.0734 |
| striker | 23 | 0.8611 | −0.3867 |
| wind | 23 | −0.2748 | 0.0676 |
| comet | 22 | 0.2574 | −0.1080 |
| earnings | 22 | −0.1301 | 0.9886 |
| frost | 22 | −0.2930 | 0.0963 |
| greenhouse | 22 | −0.7141 | −0.5845 |
| launch | 22 | 0.2420 | −0.1535 |
| portfolio | 22 | −0.1392 | 1.030 |
| rain | 22 | −0.3375 | 0.0570 |
| rocket | 22 | 0.2855 | −0.2264 |
| telescope | 22 | 0.2295 | −0.1470 |
| bread | 21 | 0.0896 | 0.0051 |
| butter | 21 | 0.0703 | 0.1889 |
| goal | 21 | 0.7120 | −0.2910 |
| season | 21 | 0.8941 | −0.4146 |
| stocks | 21 | −0.1259 | 1.018 |
View data
| Cosine similarity | Word | Neighbor |
|---|---|---|
| 0.8152 | small | people |
| 0.7044 | small | lunar |
| 0.7042 | small | index |
| 0.6911 | small | good |
| 0.6476 | small | trading |
| 0.9687 | sugar | loaf |
| 0.9330 | sugar | recipe |
| 0.9186 | sugar | knead |
| 0.9175 | sugar | yeast |
| 0.9112 | sugar | pastry |
| 0.7013 | today | again |
| 0.6723 | today | big |
| 0.6256 | today | new |
| 0.5749 | today | referee |
| 0.4542 | today | said |
| 0.7403 | new | week |
| 0.7071 | new | again |
| 0.7010 | new | yeast |
| 0.6445 | new | knead |
| 0.6256 | new | today |
| 0.8433 | people | good |
| 0.8152 | people | small |
| 0.7941 | people | lunar |
| 0.7462 | people | mission |
| 0.7450 | people | rocket |
Assumptions
- Enough text — 1989 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 |
|---|---|---|---|
| small | 1 | people | 0.8152 |
| small | 2 | lunar | 0.7044 |
| small | 3 | index | 0.7042 |
| small | 4 | good | 0.6911 |
| small | 5 | trading | 0.6476 |
| sugar | 1 | loaf | 0.9687 |
| sugar | 2 | recipe | 0.9330 |
| sugar | 3 | knead | 0.9186 |
| sugar | 4 | yeast | 0.9175 |
| sugar | 5 | pastry | 0.9112 |
| today | 1 | again | 0.7013 |
| today | 2 | big | 0.6723 |
| today | 3 | new | 0.6256 |
| today | 4 | referee | 0.5749 |
| today | 5 | said | 0.4542 |
| new | 1 | week | 0.7403 |
| new | 2 | again | 0.7071 |
| new | 3 | yeast | 0.7010 |
| new | 4 | knead | 0.6445 |
| new | 5 | today | 0.6256 |
| people | 1 | good | 0.8433 |
| people | 2 | small | 0.8152 |
| people | 3 | lunar | 0.7941 |
| people | 4 | mission | 0.7462 |
| people | 5 | rocket | 0.7450 |
- 3 rows have no text (or no words) and are left out.
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 5a91c340b01ac418
# Dataset: ml_topics (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_topics.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(10L, V)
if (DIM < 10) warnings <- c(warnings, sprintf("Only %d words are kept, so the vectors have %d dimensions instead of 10.", V, V))
# %% Fit
METHOD <- "ppmi_svd"
SEED <- 42
EPOCHS <- NULL
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")) {
fit <- cs_wv_sgns(ids, counts, 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")
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 <- ""
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 <- 5
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]
}
}
# %% Artifacts: one row per word
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.word_vectors/ppmi_topics/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]
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"))
))
PPMI-SVD: 10-dimensional vectors for 84 words from 1989 words of text. Closest to “small”: people (0.82).
- Words with vectors
- 84
- Words of text
- 1,989
- Dimensions
- 10
- PPMI kept by these dimensions
- 0.8266
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough text — 1989 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 |
|---|---|---|---|
| small | 1 | people | 0.8152 |
| small | 2 | lunar | 0.7044 |
| small | 3 | index | 0.7042 |
| small | 4 | good | 0.6911 |
| small | 5 | trading | 0.6476 |
| sugar | 1 | loaf | 0.9687 |
| sugar | 2 | recipe | 0.9330 |
| sugar | 3 | knead | 0.9186 |
| sugar | 4 | yeast | 0.9175 |
| sugar | 5 | pastry | 0.9112 |
| today | 1 | again | 0.7013 |
| today | 2 | big | 0.6723 |
| today | 3 | new | 0.6256 |
| today | 4 | referee | 0.5749 |
| today | 5 | said | 0.4542 |
| new | 1 | week | 0.7403 |
| new | 2 | again | 0.7071 |
| new | 3 | yeast | 0.7010 |
| new | 4 | knead | 0.6445 |
| new | 5 | today | 0.6256 |
| people | 1 | good | 0.8433 |
| people | 2 | small | 0.8152 |
| people | 3 | lunar | 0.7941 |
| people | 4 | mission | 0.7462 |
| people | 5 | rocket | 0.7450 |
- 3 rows have no text (or no words) and are left out.
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 5a91c340b01ac418
# Dataset: ml_topics (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_topics.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(10, V)
if DIM < 10:
warnings.append(f"Only {V} words are kept, so the vectors have {V} dimensions instead of 10.")
# %% Fit
METHOD = "ppmi_svd"
SEED = 42
EPOCHS = None
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"):
vectors, final_loss = wv.sgns(ids, counts, 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 = ""
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 = 5
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]
# %% Artifacts: one row per word
out = csml.out_dir("target/academy-parity/run-8142/discover.word_vectors/ppmi_topics/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])
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"}],
})
The map shows the first two principal components of the vectors. Its axes have no meaning, and another seed or method rotates the picture, so compare neighbors rather than coordinates.
View data
| PC 1 | PC 2 | level | feature | rows |
|---|---|---|---|---|
| −0.8520 | 0.2910 | Mon | weekday | 1,436 |
| −0.6840 | 0.0770 | Tue | weekday | 1,499 |
| −0.6460 | −0.0950 | Wed | weekday | 1,301 |
| −0.5400 | −0.1380 | Thu | weekday | 1,520 |
| −0.2430 | −0.4700 | Fri | weekday | 1,517 |
| 1.366 | 0.1560 | Sat | weekday | 1,424 |
| 1.281 | 0.4470 | Sun | weekday | 1,493 |
| 0.5590 | −0.5520 | urban | store type | 4,200 |
| 0.1730 | −0.7490 | suburban | store type | 3,100 |
| −0.6620 | 0.6650 | rural | store type | 1,600 |
| 0.9010 | 0.8360 | outlet | store type | 900 |
PMI only depends on ratios of counts. Repeating every row of the text doubles every count and changes nothing: the largest singular value stays 23.008 (it was 23.008). Duplicated documents still matter, though, because a pair seen in one repeated template looks as strong as a pair seen in many independent texts.
Check yourself
You widen the window from 2 to 10 words. What changes in the neighbors?
Show the answer
Answer: b
Small windows see grammar and role; large windows see the topic of the surrounding sentence.
Concepts in this lesson