Skip to content

CDiscover · discover.word_vectors

Word vectors

Which words are used in similar contexts in this text?

Learns a vector for every frequent word of a text column from the words around it, so words used in similar contexts end up close together. PPMI-SVD (a factorization of positive pointwise mutual information, exact and quick, best on small collections), skip-gram or CBOW with negative sampling (word2vec) or GloVe. Shows each query word's nearest neighbors by cosine similarity and a map of the most frequent words. Random starts and noise words come from the shared random stream, so Python and R agree.

Verified in Python and R Python and R agree to 6 decimals Also called word embeddings, word2vec, fastText…

A real result

Example “Ppmi topics”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

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

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

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

View data
WordCountComponent 1Component 2
small380.00520.1561
sugar370.08570.1132
today35−0.0279−0.0814
new320.14210.0744
people320.0834−0.0855
astronaut310.3368−0.1716
said31−0.1041−0.0828
again30−0.09470.0420
dividend30−0.15270.9911
late30−0.12280.1418
early290.19060.0611
stadium290.8191−0.3674
big28−0.06440.2080
galaxy280.2859−0.1354
knead280.10850.1121
orbit280.2645−0.1396
pastry280.05830.0910
pruning28−0.7696−0.6215
week28−0.13120.1371
clouds27−0.35920.0622
investors27−0.12290.8948
rates27−0.13730.9100
coach260.7984−0.3907
compost26−0.6854−0.5783
crust260.10420.1657
inflation26−0.10220.9529
loaf260.0328−0.0117
planet260.2762−0.1198
probe260.2659−0.1270
seeds26−0.8625−0.6852
sunshine26−0.4189−0.0258
match250.8432−0.3826
midfield250.8666−0.3720
oven250.14630.1501
recipe250.08450.2387
yields25−0.12731.027
bond24−0.09060.8768
good240.0901−0.1243
mulch24−0.8669−0.6414
hedge23−0.7133−0.5977
mission230.3357−0.1648
really230.2796−0.2216
shares23−0.13570.9194
storm23−0.35650.0734
striker230.8611−0.3867
wind23−0.27480.0676
comet220.2574−0.1080
earnings22−0.13010.9886
frost22−0.29300.0963
greenhouse22−0.7141−0.5845
launch220.2420−0.1535
portfolio22−0.13921.030
rain22−0.33750.0570
rocket220.2855−0.2264
telescope220.2295−0.1470
bread210.08960.0051
butter210.07030.1889
goal210.7120−0.2910
season210.8941−0.4146
stocks21−0.12591.018
Nearest wordsWhich words or phrases appear most in a text column, overall or by group?
View data
Cosine similarityWordNeighbor
0.8152smallpeople
0.7044smalllunar
0.7042smallindex
0.6911smallgood
0.6476smalltrading
0.9687sugarloaf
0.9330sugarrecipe
0.9186sugarknead
0.9175sugaryeast
0.9112sugarpastry
0.7013todayagain
0.6723todaybig
0.6256todaynew
0.5749todayreferee
0.4542todaysaid
0.7403newweek
0.7071newagain
0.7010newyeast
0.6445newknead
0.6256newtoday
0.8433peoplegood
0.8152peoplesmall
0.7941peoplelunar
0.7462peoplemission
0.7450peoplerocket

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

WordRankNeighborCosine similarity
small1people0.8152
small2lunar0.7044
small3index0.7042
small4good0.6911
small5trading0.6476
sugar1loaf0.9687
sugar2recipe0.9330
sugar3knead0.9186
sugar4yeast0.9175
sugar5pastry0.9112
today1again0.7013
today2big0.6723
today3new0.6256
today4referee0.5749
today5said0.4542
new1week0.7403
new2again0.7071
new3yeast0.7010
new4knead0.6445
new5today0.6256
people1good0.8433
people2small0.8152
people3lunar0.7941
people4mission0.7462
people5rocket0.7450
  • 3 rows have no text (or no words) and are left out.
Python

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

WordRankNeighborCosine similarity
small1people0.8152
small2lunar0.7044
small3index0.7042
small4good0.6911
small5trading0.6476
sugar1loaf0.9687
sugar2recipe0.9330
sugar3knead0.9186
sugar4yeast0.9175
sugar5pastry0.9112
today1again0.7013
today2big0.6723
today3new0.6256
today4referee0.5749
today5said0.4542
new1week0.7403
new2again0.7071
new3yeast0.7010
new4knead0.6445
new5today0.6256
people1good0.8433
people2small0.8152
people3lunar0.7941
people4mission0.7462
people5rocket0.7450
  • 3 rows have no text (or no words) and are left out.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Ppmi topicsml_topics · text: text
  • Sgns topicsml_topics · text: text
  • Cbow corpus queriesml_corpus · text: text
  • Glove topicsml_topics · text: text
  • Ppmi corpus whitespaceml_corpus · text: text
  • Ppmi topics repeatedtxt1_topics_x2 · text: text
  • Sgns subword oovml_corpus · text: text
  • Cbow subword small bucketsml_topics · text: text

In the guides

Where it sits in the decision guides

  • Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
  • Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Textcategorical · 1 column
The text column; each row is one document. Windows never cross from one row to the next.

Choices you make

model

Methoddefault ppmi_svd

PPMI-SVD is exact and works well on small collections; skip-gram, CBOW and GloVe need more text.

  • PPMI-SVD (counts, exact)(default) — Positive pointwise mutual information of window counts, factorized by SVD (Levy, Goldberg & Dagan 2015).
  • Skip-gram with negative sampling — word2vec: each word predicts the words around it against randomly drawn noise words.
  • CBOW with negative sampling — word2vec: the average of the surrounding words predicts the word in the middle; quicker than skip-gram.
  • GloVe — Fits word vectors to the logarithm of distance-weighted co-occurrence counts (Pennington et al. 2014).
Dimensionsdefault 50

Length of each word vector. Small collections need few dimensions; capped at the vocabulary size.

Context windowdefault 4

How many words on each side count as context. Small windows find words with the same role; large ones find words on the same topic.

Passes over the textdefault —

Training passes. Small collections need more passes; PPMI-SVD needs none.

Subwords (fastText)default off

Each word also learns from its character n-grams (fastText), so rare words, typos and looked-up words outside the vocabulary get vectors.

Advanced

Noise words per pairdefault 5

Noise words drawn (from word frequencies to the power 0.75) for every word pair.

Learning ratedefault —

Starting step size. Skip-gram and CBOW decay it linearly to almost zero; GloVe adapts it per word (AdaGrad).

Shortest n-gramdefault 3

Fewest characters in a subword piece, counting the < and > that mark a word's start and end.

Longest n-gramdefault 6

Most characters in a subword piece; fastText uses 3 to 6.

Hash bucketsdefault 2000000

Pieces are hashed into this many slots; pieces that share a slot share a vector. Only slots in use take memory.

preprocess

Minimum word countdefault 2

Words seen fewer times are dropped before windows are formed.

Vocabulary sizedefault 2000

Largest vocabulary kept, by frequency.

Wordsdefault words

How text is split into words.

  • Runs of letters and digits(default) — Punctuation is dropped.
  • Split on spaces — Keeps punctuation attached; for text that was tokenized before it reached the app.
Ignore casedefault on

Lower-case the text first, so "The" and "the" are one word.

options

Words to look updefault —

Words whose nearest neighbors to list, separated by commas. Empty lists the five most frequent words (at most nine).

Neighbors per worddefault 5

How many nearest words to list for each looked-up word.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Enough text

    Word vectors need a lot of text: with fewer than about 10,000 words, neighbors are noisy and change with the settings.

  • The window sets the kind of similarity

    Small windows group words that play the same role ("Monday", "Tuesday"); large windows group words about the same topic.

  • Coordinates are arbitrary

    Vectors can be rotated or flipped without changing their meaning; compare neighbors and similarities, not single coordinates.

What it reports

n_docs
Rows with words, words of text after rare words were removed, and how many words get a vector.
n_dropped
Rows with words, words of text after rare words were removed, and how many words get a vector.
n_tokens
Rows with words, words of text after rare words were removed, and how many words get a vector.
vocab_size
Rows with words, words of text after rare words were removed, and how many words get a vector.
dim
A list of numbers per word, learned from the words around it, so words used in similar contexts get similar vectors.
window
How many words on each side count as a word's context; windows never cross from one row to the next.
method
A list of numbers per word, learned from the words around it, so words used in similar contexts get similar vectors.
final_loss
word2vec: each word's vector is trained to predict nearby words against randomly drawn noise words (CBOW predicts the middle word).
sv_share
log of how much more often two words share a window than chance predicts, with negative values set to 0.

Per group, level or term: sv[<k>], nearest[<word>], similarity[<word>], subword_<stat>

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses pandas, numpy, codesplash; R uses nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines run the same twins (codesplash.text.word_vectors ↔ codesplashr R/text_word_vectors.R) with starting vectors, noise words and GloVe's cell order from the shared Wichmann–Hill stream; dot products sum in a different order (NumPy's BLAS vs R's sum), so trained vectors agree to rounding, not bit for bit.
  • PPMI-SVD uses each engine's LAPACK SVD; column signs are fixed by each column's largest entry.
Python

The exact script CodeSplash ran for example “Ppmi topics” · 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"}],
})
R

The exact script CodeSplash ran for example “Ppmi topics” · 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"))
))

Sources

  • Mikolov T, Sutskever I, Chen K, Corrado G, Dean J (2013). Distributed representations of words and phrases and their compositionality. NeurIPS 26, 3111–3119.
  • Levy O, Goldberg Y (2014). Neural word embedding as implicit matrix factorization. NeurIPS 27, 2177–2185.
  • Levy O, Goldberg Y, Dagan I (2015). Improving distributional similarity with lessons learned from word embeddings. TACL 3, 211–225.
  • Pennington J, Socher R, Manning CD (2014). GloVe: global vectors for word representation. EMNLP 2014, 1532–1543.
  • Bojanowski P, Grave E, Joulin A, Mikolov T (2017). Enriching word vectors with subword information. TACL 5, 135–146 (fastText).

From the CodeSplash method registry · discover.word_vectors v1.1.0.