Word2vec and GloVe: vectors from the company words keep
CBOW and skip-gram learn word vectors by predicting neighbors with a few sampled noise words; GloVe fits log co-occurrence counts. Train all three on the same text and see why their neighbor lists disagree.
What runs in CodeSplash
- LNG003Word2vec continuous bag of words (CBOW) Runs in CodeSplash
- LNG004Skip-gram with negative sampling (SGNS) Runs in CodeSplash
- LNG005GloVe Runs in CodeSplash
- Word vectors Verified in Python and R
You will be able to
- Describe the CBOW and skip-gram prediction tasks and what negative sampling replaces
- Write GloVe's weighted least-squares objective and say why zero counts drop out
- Relate prediction-based vectors to factorizing a PMI matrix
- Read nearest-neighbor lists as noisy hints, not definitions
Two prediction games
ReadWord2vec drops the neural language model's hidden layer and keeps only word vectors. Slide a window over the text. CBOW averages the vectors of the words around a position and predicts the word in the middle. Skip-gram does the reverse: from the middle word it predicts each word around it.
In the reference CBOW program, two context vectors average to 0.5 and 0.5 in each coordinate, and the loss for the true center word is 0.369. Words that keep the same company end up with similar vectorsWord vectorA list of numbers per word, learned from the words around it, so words used in similar contexts get similar vectors..
Noise words instead of a full softmax
ReadPredicting one word out of the whole vocabulary is the expensive softmax again. Negative samplingNegative samplingTrains word vectors by telling real neighbor pairs from a few random noise words, instead of a softmax over the whole vocabulary. turns it into a few yes/no questions: is this pair a real neighbor pair, or a word drawn at random?
The real pair is pulled together and the K noise words pushed away. With one real pair and two noise words, the reference program's skip-gramSkip-gram with negative samplingword2vec: each word's vector is trained to predict nearby words against randomly drawn noise words (CBOW predicts the middle word). loss is 1.821. Noise words are drawn from word frequencies raised to the power ¾, so rare words get picked a little more often than their counts suggest.
GloVe: fit the counts directly
ReadGloVeGloVeWord vectors fitted so their dot products match the log of distance-weighted co-occurrence counts. counts how often each pair of words occurs within the window, then fits vectors whose dot products match the log counts:
The weight f gives rare pairs less say, caps frequent ones, and is zero when a pair never occurs, so log 0 never enters. For one pair seen 8 times, the reference program's weighted squared error is 0.424.
Prediction and counting meet
ReadSkip-gram with negative sampling turns out to approximate a factorization of a word-by-context matrix of pointwise mutual informationPPMIlog of how much more often two words share a window than chance predicts, with negative values set to 0., shifted by the log of the number of noise words. So the count route can do the same job exactly: build the positive PMI matrix and take its truncated SVD.
That is why CodeSplash's Word vectors method defaults to PPMI-SVD: no random start, the same vectors on every run and in both engines. Skip-gram, CBOW and GloVe are options beside it.
Reference · LNG004 · Runs in CodeSplashSkip-gram with negative sampling (SGNS)Predicts neighboring words from a center word, emphasizing useful distributional representations rather than normalized sentence likelihoods. Negative sampling makes a large vocabulary practical.Three methods, one text
ReadSkip-gram: 10-dimensional vectors for 84 words from 1989 words of text. Closest to “small”: good (0.98).
- Words with vectors
- 84
- Words of text
- 1,989
- Dimensions
- 10
- Loss in the last pass
- 2.312
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.0355 | 0.0531 |
| sugar | 37 | −0.3111 | 0.2326 |
| today | 35 | 0.1611 | −0.1340 |
| new | 32 | −0.4253 | 0.2170 |
| people | 32 | −0.2844 | −0.2508 |
| astronaut | 31 | −1.421 | −0.8359 |
| said | 31 | 0.1865 | −0.2725 |
| again | 30 | 0.1985 | 0.0656 |
| dividend | 30 | −0.1123 | 1.191 |
| late | 30 | −0.0068 | 0.2096 |
| early | 29 | −0.2679 | 0.0913 |
| stadium | 29 | 0.2382 | −0.1894 |
| big | 28 | −0.1824 | 0.1776 |
| galaxy | 28 | −1.448 | −0.6594 |
| knead | 28 | −0.2381 | 0.2904 |
| orbit | 28 | −1.433 | −0.8173 |
| pastry | 28 | −0.4610 | 0.0688 |
| pruning | 28 | 1.285 | −0.7916 |
| week | 28 | 0.2592 | 0.1079 |
| clouds | 27 | 0.2280 | 0.3264 |
| investors | 27 | −0.0137 | 1.086 |
| rates | 27 | −0.0810 | 0.9165 |
| coach | 26 | 0.4910 | −0.1537 |
| compost | 26 | 1.066 | −0.7244 |
| crust | 26 | −0.4202 | 0.3162 |
| inflation | 26 | −0.1778 | 1.160 |
| loaf | 26 | −0.1292 | 0.1053 |
| planet | 26 | −1.309 | −0.7273 |
| probe | 26 | −1.382 | −0.7110 |
| seeds | 26 | 1.493 | −0.7011 |
| sunshine | 26 | 0.4164 | 0.2032 |
| match | 25 | 0.1155 | −0.1180 |
| midfield | 25 | 0.0820 | −0.1955 |
| oven | 25 | −0.3607 | 0.3373 |
| recipe | 25 | −0.2345 | 0.2914 |
| yields | 25 | −0.0912 | 1.002 |
| bond | 24 | 0.0540 | 0.8929 |
| good | 24 | −0.0273 | −0.1368 |
| mulch | 24 | 1.256 | −0.6458 |
| hedge | 23 | 1.186 | −0.5733 |
| mission | 23 | −1.076 | −0.6059 |
| really | 23 | 0.0132 | −0.2391 |
| shares | 23 | −0.0566 | 0.8749 |
| storm | 23 | 0.2637 | 0.2776 |
| striker | 23 | 0.3462 | −0.1596 |
| wind | 23 | 0.0066 | 0.3286 |
| comet | 22 | −1.117 | −0.5221 |
| earnings | 22 | −0.0668 | 0.8882 |
| frost | 22 | 0.1190 | 0.3285 |
| greenhouse | 22 | 1.265 | −0.5898 |
| launch | 22 | −0.9856 | −0.7857 |
| portfolio | 22 | −0.0921 | 1.109 |
| rain | 22 | 0.1669 | 0.2399 |
| rocket | 22 | −1.157 | −0.7906 |
| telescope | 22 | −1.117 | −0.5789 |
| bread | 21 | 0.1522 | 0.0677 |
| butter | 21 | −0.1359 | 0.2046 |
| goal | 21 | 0.2071 | 0.0078 |
| season | 21 | 0.2665 | −0.0924 |
| stocks | 21 | −0.0922 | 1.046 |
View data
| Cosine similarity | Word | Neighbor |
|---|---|---|
| 0.9817 | small | good |
| 0.9722 | small | big |
| 0.9649 | small | today |
| 0.9588 | small | again |
| 0.9531 | small | really |
| 0.9944 | sugar | knead |
| 0.9941 | sugar | crust |
| 0.9910 | sugar | recipe |
| 0.9908 | sugar | oven |
| 0.9860 | sugar | pastry |
| 0.9868 | today | said |
| 0.9845 | today | good |
| 0.9790 | today | really |
| 0.9786 | today | again |
| 0.9649 | today | small |
| 0.9614 | new | early |
| 0.9587 | new | flour |
| 0.9448 | new | dough |
| 0.9443 | new | big |
| 0.9410 | new | yeast |
| 0.9678 | people | good |
| 0.9577 | people | really |
| 0.9482 | people | small |
| 0.9402 | people | lunar |
| 0.9210 | people | big |
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 | good | 0.9817 |
| small | 2 | big | 0.9722 |
| small | 3 | today | 0.9649 |
| small | 4 | again | 0.9588 |
| small | 5 | really | 0.9531 |
| sugar | 1 | knead | 0.9944 |
| sugar | 2 | crust | 0.9941 |
| sugar | 3 | recipe | 0.9910 |
| sugar | 4 | oven | 0.9908 |
| sugar | 5 | pastry | 0.9860 |
| today | 1 | said | 0.9868 |
| today | 2 | good | 0.9845 |
| today | 3 | really | 0.9790 |
| today | 4 | again | 0.9786 |
| today | 5 | small | 0.9649 |
| new | 1 | early | 0.9614 |
| new | 2 | flour | 0.9587 |
| new | 3 | dough | 0.9448 |
| new | 4 | big | 0.9443 |
| new | 5 | yeast | 0.9410 |
| people | 1 | good | 0.9678 |
| people | 2 | really | 0.9577 |
| people | 3 | small | 0.9482 |
| people | 4 | lunar | 0.9402 |
| people | 5 | big | 0.9210 |
- 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 96eea854e44a66c5
# 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 <- "sgns"
SEED <- 42
EPOCHS <- 10
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/sgns_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"))
))
Skip-gram: 10-dimensional vectors for 84 words from 1989 words of text. Closest to “small”: good (0.98).
- Words with vectors
- 84
- Words of text
- 1,989
- Dimensions
- 10
- Loss in the last pass
- 2.312
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 | good | 0.9817 |
| small | 2 | big | 0.9722 |
| small | 3 | today | 0.9649 |
| small | 4 | again | 0.9588 |
| small | 5 | really | 0.9531 |
| sugar | 1 | knead | 0.9944 |
| sugar | 2 | crust | 0.9941 |
| sugar | 3 | recipe | 0.9910 |
| sugar | 4 | oven | 0.9908 |
| sugar | 5 | pastry | 0.9860 |
| today | 1 | said | 0.9868 |
| today | 2 | good | 0.9845 |
| today | 3 | really | 0.9790 |
| today | 4 | again | 0.9786 |
| today | 5 | small | 0.9649 |
| new | 1 | early | 0.9614 |
| new | 2 | flour | 0.9587 |
| new | 3 | dough | 0.9448 |
| new | 4 | big | 0.9443 |
| new | 5 | yeast | 0.9410 |
| people | 1 | good | 0.9678 |
| people | 2 | really | 0.9577 |
| people | 3 | small | 0.9482 |
| people | 4 | lunar | 0.9402 |
| people | 5 | big | 0.9210 |
- 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 96eea854e44a66c5
# 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 = "sgns"
SEED = 42
EPOCHS = 10
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/sgns_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"}],
})
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
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"}],
})
GloVe: 10-dimensional vectors for 84 words from 1989 words of text. Closest to “small”: telescope (0.58).
- Words with vectors
- 84
- Words of text
- 1,989
- Dimensions
- 10
- Loss in the last pass
- 0.0132
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.0136 | −0.0089 |
| sugar | 37 | −0.0527 | 0.0897 |
| today | 35 | 0.0179 | 0.0177 |
| new | 32 | 0.0549 | −0.0039 |
| people | 32 | −0.0079 | −0.1251 |
| astronaut | 31 | 0.1283 | 0.0693 |
| said | 31 | −0.0160 | −0.0141 |
| again | 30 | −0.0356 | −0.0420 |
| dividend | 30 | 0.0923 | 0.1159 |
| late | 30 | −0.0366 | 0.0636 |
| early | 29 | −0.0081 | 0.0148 |
| stadium | 29 | −0.0624 | −0.0601 |
| big | 28 | 0.0569 | −0.1205 |
| galaxy | 28 | 0.1195 | −0.0147 |
| knead | 28 | −0.0508 | 0.1055 |
| orbit | 28 | 0.1484 | 0.0660 |
| pastry | 28 | −0.1029 | 0.0056 |
| pruning | 28 | −0.1087 | 0.0259 |
| week | 28 | 0.0267 | 0.1014 |
| clouds | 27 | 0.0210 | 0.0199 |
| investors | 27 | 0.0391 | −0.0642 |
| rates | 27 | 0.0469 | −0.0991 |
| coach | 26 | −0.0664 | −0.0540 |
| compost | 26 | −0.1040 | −0.1152 |
| crust | 26 | −0.0177 | 0.0209 |
| inflation | 26 | 0.0382 | −0.0048 |
| loaf | 26 | −0.0119 | 0.0597 |
| planet | 26 | 0.1323 | −0.0352 |
| probe | 26 | 0.1017 | −0.0200 |
| seeds | 26 | −0.1055 | −0.0592 |
| sunshine | 26 | 0.0016 | −0.0686 |
| match | 25 | 0.1067 | −0.0287 |
| midfield | 25 | −0.0004 | −0.0919 |
| oven | 25 | −0.0699 | 0.0250 |
| recipe | 25 | −0.0324 | 0.1458 |
| yields | 25 | 0.0456 | −0.0022 |
| bond | 24 | −0.0145 | 0.0284 |
| good | 24 | −0.0189 | −0.0732 |
| mulch | 24 | −0.1352 | 0.0306 |
| hedge | 23 | −0.1320 | 0.0324 |
| mission | 23 | −0.0230 | 0.0383 |
| really | 23 | 0.0059 | −0.0383 |
| shares | 23 | 0.0774 | −0.0473 |
| storm | 23 | 0.0328 | 0.0099 |
| striker | 23 | −0.0838 | −0.0553 |
| wind | 23 | 0.0563 | −0.0246 |
| comet | 22 | 0.0260 | −0.0066 |
| earnings | 22 | 0.0906 | −0.0677 |
| frost | 22 | 0.0990 | −0.0153 |
| greenhouse | 22 | −0.1299 | −0.0356 |
| launch | 22 | 0.0424 | 0.1146 |
| portfolio | 22 | 0.0425 | 0.0651 |
| rain | 22 | 0.0607 | −0.0761 |
| rocket | 22 | 0.0819 | −0.0364 |
| telescope | 22 | −0.0353 | −0.0574 |
| bread | 21 | −0.0012 | 0.0091 |
| butter | 21 | −0.0549 | 0.1293 |
| goal | 21 | 0.0049 | 0.0168 |
| season | 21 | −0.0944 | −0.0350 |
| stocks | 21 | 0.0657 | 0.0742 |
View data
| Cosine similarity | Word | Neighbor |
|---|---|---|
| 0.5780 | small | telescope |
| 0.5125 | small | rates |
| 0.5089 | small | tomatoes |
| 0.4826 | small | trading |
| 0.4761 | small | seeds |
| 0.6169 | sugar | loaf |
| 0.4870 | sugar | watering |
| 0.4692 | sugar | butter |
| 0.4565 | sugar | yeast |
| 0.4115 | sugar | oven |
| 0.7733 | today | portfolio |
| 0.7545 | today | bond |
| 0.5541 | today | lunar |
| 0.5031 | today | match |
| 0.4737 | today | investors |
| 0.6913 | new | clouds |
| 0.6465 | new | wind |
| 0.5506 | new | frost |
| 0.4672 | new | weeds |
| 0.4606 | new | dough |
| 0.7273 | people | roses |
| 0.7210 | people | big |
| 0.6770 | people | satellite |
| 0.5929 | people | stadium |
| 0.5662 | people | trading |
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 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 |
|---|---|---|---|
| small | 1 | telescope | 0.5780 |
| small | 2 | rates | 0.5125 |
| small | 3 | tomatoes | 0.5089 |
| small | 4 | trading | 0.4826 |
| small | 5 | seeds | 0.4761 |
| sugar | 1 | loaf | 0.6169 |
| sugar | 2 | watering | 0.4870 |
| sugar | 3 | butter | 0.4692 |
| sugar | 4 | yeast | 0.4565 |
| sugar | 5 | oven | 0.4115 |
| today | 1 | portfolio | 0.7733 |
| today | 2 | bond | 0.7545 |
| today | 3 | lunar | 0.5541 |
| today | 4 | match | 0.5031 |
| today | 5 | investors | 0.4737 |
| new | 1 | clouds | 0.6913 |
| new | 2 | wind | 0.6465 |
| new | 3 | frost | 0.5506 |
| new | 4 | weeds | 0.4672 |
| new | 5 | dough | 0.4606 |
| people | 1 | roses | 0.7273 |
| people | 2 | big | 0.7210 |
| people | 3 | satellite | 0.6770 |
| people | 4 | stadium | 0.5929 |
| people | 5 | trading | 0.5662 |
- 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 0d9e0b30bbdebdaa
# 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 <- 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(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 <- "glove"
SEED <- 42
EPOCHS <- 20
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/glove_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"))
))
GloVe: 10-dimensional vectors for 84 words from 1989 words of text. Closest to “small”: telescope (0.58).
- Words with vectors
- 84
- Words of text
- 1,989
- Dimensions
- 10
- Loss in the last pass
- 0.0132
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 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 |
|---|---|---|---|
| small | 1 | telescope | 0.5780 |
| small | 2 | rates | 0.5125 |
| small | 3 | tomatoes | 0.5089 |
| small | 4 | trading | 0.4826 |
| small | 5 | seeds | 0.4761 |
| sugar | 1 | loaf | 0.6169 |
| sugar | 2 | watering | 0.4870 |
| sugar | 3 | butter | 0.4692 |
| sugar | 4 | yeast | 0.4565 |
| sugar | 5 | oven | 0.4115 |
| today | 1 | portfolio | 0.7733 |
| today | 2 | bond | 0.7545 |
| today | 3 | lunar | 0.5541 |
| today | 4 | match | 0.5031 |
| today | 5 | investors | 0.4737 |
| new | 1 | clouds | 0.6913 |
| new | 2 | wind | 0.6465 |
| new | 3 | frost | 0.5506 |
| new | 4 | weeds | 0.4672 |
| new | 5 | dough | 0.4606 |
| people | 1 | roses | 0.7273 |
| people | 2 | big | 0.7210 |
| people | 3 | satellite | 0.6770 |
| people | 4 | stadium | 0.5929 |
| people | 5 | trading | 0.5662 |
- 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 0d9e0b30bbdebdaa
# 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 = 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(10, V)
if DIM < 10:
warnings.append(f"Only {V} words are kept, so the vectors have {V} dimensions instead of 10.")
# %% Fit
METHOD = "glove"
SEED = 42
EPOCHS = 20
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/glove_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"}],
})
All three read the same 1,989 words and learn vectors for the same 84. The nearest word to "small" is "good" for skip-gram, "people" for PPMI-SVD and "telescope" for GloVe.
On a text this small, neighbor lists are noisy and method-dependent. Treat them as hints to check against the text, and compare similarities, never single coordinates.
Maps of vectors
ExploreAExplorable · What t-SNE and UMAP maps don't show
What can you safely read from a t-SNE or UMAP picture?
One group here may be far wider than another in the original space. In the map, that difference in size will be…
Ten-dimensional data
Method
Commit your prediction above to see the result
Make your prediction to see the result.
A word map squeezes many dimensions into two. Choose Pure noise, no clusters at all and the map still draws islands; choose Two close clusters and one far away and the gaps between islands stop meaning distance. Read neighbors and similarities from the vectors, not from the picture.
Window size
PredictPredict first
You train skip-gram twice, with a window of 2 and a window of 10 words on each side. With the small window, what do the neighbors of "small" tend to be?
Reveal
Words that play the same role: other adjectives that fill the same slot. A wide window mixes in everything nearby, so neighbors drift toward the topic ("telescope", "lunar") rather than the grammar.
Where it stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| CBOW (LNG003) | Runs in CodeSplash: Word vectors, Method CBOW |
| Skip-gram with negative sampling (LNG004) | Runs in CodeSplash: Word vectors, Method Skip-gram; PPMI-SVD is the default |
| GloVe (LNG005) | Runs in CodeSplash: Word vectors, Method GloVe |
Check: word vectors
CheckpointCheck yourself
What does CBOW predict, and from what?
Show the answer
Answer: a
CBOW (continuous bag of words) averages the context, losing word order inside the window, and predicts the middle word. Skip-gram goes the other way.
Check yourself
"dog bites man" and "man bites dog" give CBOW the same training signal for the center word "bites". Why?
Show the answer
Answer: b
An average doesn't care about order. That is the "bag of words" in CBOW's name.
Check yourself
What does negative sampling replace in skip-gram training?
Show the answer
Answer: c
Each real pair is contrasted with K sampled noise words, so a training step costs K + 1 dot products instead of one per vocabulary word.
Check yourself
Why can CodeSplash offer PPMI-SVD as an exact alternative to skip-gram with negative sampling?
Show the answer
Answer: b
The count route reaches similar geometry without random sampling, so it is reproducible run to run and across engines. Coordinates still differ by a rotation.
Check yourself
In GloVe, what happens to word pairs that never occur together?
Show the answer
Answer: b
GloVe fits log counts, and log 0 is undefined; the weighting function is zero at zero, so only observed pairs are fitted.
Check yourself
Why does GloVe cap the weight of very frequent pairs such as "of the"?
Show the answer
Answer: a
f(x) grows with the count but stops at 1 above a maximum count, keeping common function-word pairs from swamping the rest.
Check yourself
Skip-gram and GloVe, trained on the same short text, give different nearest neighbors for "small". What is the right reading?
Show the answer
Answer: b
Different objectives, seeds and weightings rearrange weak evidence differently. More text, or agreement across methods, makes neighbors worth trusting.
Recap
Recap- CBOW predicts the center word from its averaged context; skip-gram predicts the context from the center.
- Negative sampling replaces the full softmax with a few noise-word checks.
- GloVe fits weighted log co-occurrence counts; zero counts drop out.
- Skip-gram approximates factorizing a shifted PMI matrix, so PPMI-SVD gives a reproducible default. All four run in Word vectors.
Concepts in this lesson