Searching and labeling texts by meaning
Find the texts that match a query by words (BM25), by meaning (sentence embeddings) or both, and sort texts into labels you name without training a model.
What runs in CodeSplash
- Semantic search (BM25, sentence embeddings, hybrid) Not verified yet
- Zero-shot text labels (sentence embeddings) Verified in Python and R
You will be able to
- Choose between word search, meaning search and hybrid search
- Read a reciprocal-rank-fusion ranking
- Label texts zero-shot and judge the labels against known ones
Read first
Two ways to find a text
ReadA column of sentences about sport, cooking and finance holds 61 texts. You want the ones about a late goal in a match.
BM25 scores the words a text shares with the query. Rare words count more than common ones, and a long text earns less for each match than a short one. Here it knows 231 distinct words. It needs no model, and it finds exact names and codes.
Dense search turns each text and the query into a sentence embeddingSentence embeddingA fixed-length vector for a whole text from a model trained so that texts with similar meaning get nearby vectors. and ranks texts by cosine similarity. Texts that say the same thing in other words still match.
Words versus meaning
PredictPredict first
The query is "football game result". No text contains "football" or "game". Which search can still put the match reports first?
Reveal
The answer: Dense search
Dense search. BM25 gives a text 0 when it shares no query word. Meaning search placed row 1 first, with a cosine similarity of 0.45.
Run it
In the app3 queries over 61 texts by words (BM25); best match for query 1: row 1.
- Texts
- 61
- Queries
- 3
- Distinct words (BM25)
- 231
Plots
View data
| BM25 score | Query | Text |
|---|---|---|
| 7.521 | Q1 | d01 |
| 7.521 | Q1 | d12 |
| 2.797 | Q1 | d07 |
| 2.188 | Q1 | d19 |
| 2.055 | Q1 | d03 |
| 6.653 | Q2 | d36 |
| 6.044 | Q2 | d27 |
| 3.856 | Q2 | d28 |
| 3.327 | Q2 | d31 |
| 2.905 | Q2 | d32 |
| 4.028 | Q3 | d50 |
| 3.784 | Q3 | d41 |
| 3.784 | Q3 | d42 |
| 3.784 | Q3 | d46 |
| 3.784 | Q3 | d57 |
Assumptions
- Words or meaning — BM25 matches shared words only; texts that use other words for the same idea score 0.
- English text — The stop list and all-MiniLM-L6-v2 are English.
Best-ranked texts
| Query | Query text | Rank | Row | doc | Text | BM25 score |
|---|---|---|---|---|---|---|
| 1 | late goal in the match | 1 | 1 | d01 | The striker scored a late goal and the team won the match at home | 7.521 |
| 1 | late goal in the match | 2 | 12 | d12 | League rivals met in a tense match that ended with a late goal | 7.521 |
| 1 | late goal in the match | 3 | 7 | d07 | The referee awarded a penalty and the striker scored the winning goal | 2.797 |
| 1 | late goal in the match | 4 | 19 | d19 | Training focused on set pieces before the derby match | 2.188 |
| 1 | late goal in the match | 5 | 3 | d03 | The coach praised the defence after a clean sheet in the league match | 2.055 |
| 2 | bake bread with flour and butter | 1 | 36 | d36 | Slice the bread and serve it warm with butter and soup | 6.653 |
| 2 | bake bread with flour and butter | 2 | 27 | d27 | Bake the bread until the crust is golden and sounds hollow | 6.044 |
| 2 | bake bread with flour and butter | 3 | 28 | d28 | Whisk the eggs with sugar then fold in the flour gently | 3.856 |
| 2 | bake bread with flour and butter | 4 | 31 | d31 | Fry the fish in butter and finish it with lemon and herbs | 3.327 |
| 2 | bake bread with flour and butter | 5 | 32 | d32 | Let the dough rest before you roll it out and bake it | 2.905 |
| 3 | interest rates | 1 | 50 | d50 | The currency weakened after the bank cut interest rates | 4.028 |
| 3 | interest rates | 2 | 41 | d41 | Shares fell as investors worried about rising interest rates | 3.784 |
| 3 | interest rates | 3 | 42 | d42 | The central bank raised interest rates to slow inflation | 3.784 |
| 3 | interest rates | 4 | 46 | d46 | Inflation eased and the bank signalled lower interest rates | 3.784 |
| 3 | interest rates | 5 | 57 | d57 | The fund manager bought bonds as interest rates peaked | 3.784 |
Ties keep row order.
Queries
| Query | Text |
|---|---|
| 1 | late goal in the match |
| 2 | bake bread with flour and butter |
| 3 | interest rates |
- 1 of 62 rows were left out because a value was missing.
- BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Semantic search (BM25, sentence embeddings, hybrid)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.semantic_search 1.1.0 · spec 611d7166eac896fa
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_bm25*, cs_search_* (twins of codesplash.text.search) and cs_minilm_embed
# %% Data (rows with a text)
TEXT <- "text"
LABEL <- "doc"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c("text", "doc")))
n_input <- nrow(df)
keep_rows <- which(!is.na(df[[TEXT]]))
df <- df[keep_rows, , drop = FALSE]
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
rows <- as.integer(keep_rows) # 1-based input rows
texts <- as.character(df[[TEXT]])
n <- length(texts)
doc_names <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else rep(NA_character_, n)
unique_names <- !is.null(LABEL) && !anyNA(doc_names) && !anyDuplicated(doc_names)
doc_label <- if (unique_names) doc_names else sprintf("Row %d", rows)
# %% Queries and settings
QUERIES <- cs_search_split_list("late goal in the match; bake bread with flour and butter; interest rates")
if (!length(QUERIES)) cs_error("CS_E_INVALID_OPTION", option = "Queries", allowed = "at least one query (separate several with semicolons)", value = "(empty)")
if (length(QUERIES) > 50) cs_error("CS_E_INVALID_OPTION", option = "Queries", allowed = "at most 50 queries", value = sprintf("%d queries", length(QUERIES)))
RETRIEVER <- "bm25"
TOP_K <- min(as.integer(5), n)
m <- length(QUERIES)
# %% Scores
bm25 <- NULL
dense <- NULL
n_terms <- NA
no_match <- integer(0)
if (RETRIEVER %in% c("bm25", "hybrid")) {
bm <- cs_bm25(texts, k1 = 1.2, b = 0.75)
if (bm$avgdl <= 0) cs_error("CS_E_UNDEFINED", what = "BM25 scores", reason = "no text has a word of two or more letters outside the common-word list")
n_terms <- cs_bm25_n_terms(bm)
bm25 <- do.call(rbind, lapply(QUERIES, function(q) cs_bm25_scores(bm, q))) # queries x texts
no_match <- which(apply(bm25, 1, function(s) !any(s > 0)))
for (j in no_match) {
warnings <- c(warnings, sprintf("Query %d (“%s”) shares no word with any text, so its BM25 ranking is just row order.", j, cs_search_snippet(QUERIES[j], 40)))
}
}
if (RETRIEVER %in% c("dense", "hybrid")) {
if (!cs_minilm_available()) cs_error("CS_WEIGHTS_MISSING", model = "all-MiniLM-L6-v2 (download it from Discover → Topics in text → Pretrained embeddings)")
model <- cs_minilm_load()
dense <- cs_search_cosine(cs_minilm_embed(QUERIES, model), cs_minilm_embed(texts, model)) # queries x texts
}
final <- if (RETRIEVER == "bm25") {
bm25
} else if (RETRIEVER == "dense") {
dense
} else {
do.call(rbind, lapply(seq_len(m), function(j) cs_search_rrf(list(cs_search_ranks(bm25[j, ]), cs_search_ranks(dense[j, ])), k = 60)))
}
final <- matrix(final, nrow = m)
# %% Rankings
retriever_label <- c(bm25 = "words (BM25)", dense = "meaning (sentence embeddings)", hybrid = "words and meaning (reciprocal rank fusion)")[[RETRIEVER]]
values <- list(n_docs = n, n_queries = m, top_k = TOP_K, retriever = retriever_label,
n_terms = n_terms, n_no_match = if (!is.null(bm25)) length(no_match) else NA)
result_rows <- list()
for (j in seq_len(m)) {
order_j <- utils::head(cs_search_ranking(final[j, ]), TOP_K)
key <- sprintf("q%d", j)
values[[sprintf("top_row[%s]", key)]] <- rows[order_j[1]]
values[[sprintf("top_score[%s]", key)]] <- final[j, order_j[1]]
for (r in seq_along(order_j)) {
i <- order_j[r]
values[[sprintf("row[%s:%d]", key, r)]] <- rows[i]
values[[sprintf("score[%s:%d]", key, r)]] <- final[j, i]
row <- list(query = j, query_text = cs_search_snippet(QUERIES[j], 60), rank = r, row = rows[i], document = doc_label[i],
text = cs_search_snippet(texts[i]), score = final[j, i])
if (RETRIEVER == "hybrid") {
row$bm25 <- bm25[j, i]
row$similarity <- dense[j, i]
}
result_rows[[length(result_rows) + 1]] <- row
}
}
score_label <- c(bm25 = "BM25 score", dense = "Cosine similarity", hybrid = "Fusion score")[[RETRIEVER]]
cols <- list(list(key = "query", label = "Query", type = "integer"), list(key = "query_text", label = "Query text", type = "string"),
list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"))
if (!is.null(LABEL)) cols <- c(cols, list(list(key = "document", label = if (unique_names) LABEL else "Document", type = "string")))
cols <- c(cols, list(list(key = "text", label = "Text", type = "string"), list(key = "score", label = score_label, type = "number")))
if (RETRIEVER == "hybrid") cols <- c(cols, list(list(key = "bm25", label = "BM25 score", type = "number"), list(key = "similarity", label = "Cosine similarity", type = "number")))
tables <- list(
list(key = "results", title = "Best-ranked texts", columns = cols, rows = result_rows,
note = paste0("Ties keep row order.", if (RETRIEVER == "hybrid") " Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings." else "")),
list(key = "queries", title = "Queries", columns = list(list(key = "query", label = "Query", type = "integer"), list(key = "text", label = "Text", type = "string")),
rows = lapply(seq_len(m), function(j) list(query = j, text = QUERIES[j])))
)
charts <- list()
if (m <= 9) { # the chart draws at most 9 panels; the table has every query
rv <- function(k) vapply(result_rows, function(r) r[[k]], if (k == "score") numeric(1) else if (k == "query") integer(1) else character(1))
charts[[1]] <- cs_chart("results", "ngram-bars", sprintf("Best-ranked texts per query (%s)", tolower(score_label)),
list(term = cs_col("Text", rv("document"), kind = "categorical"), count = cs_col(score_label, rv("score")),
group = cs_col("Query", sprintf("Q%d", rv("query")), kind = "categorical", levels = sprintf("Q%d", seq_len(m)))),
controls = list(top = max(3L, TOP_K)))
}
assumptions <- list(
list(key = "words_vs_meaning", label = "Words or meaning", status = "info",
detail = c(bm25 = "BM25 matches shared words only; texts that use other words for the same idea score 0.",
dense = "Dense search matches meaning; exact names, numbers and codes can rank lower than with BM25.",
hybrid = "Hybrid search combines both rankings, so a text matched by words or by meaning can rise.")[[RETRIEVER]]),
list(key = "language", label = "English text", status = "info", detail = "The stop list and all-MiniLM-L6-v2 are English.")
)
summary <- sprintf("%d quer%s over %d texts by %s; best match for query 1: row %d.", m, if (m == 1) "y" else "ies", n, retriever_label, values[["top_row[q1]"]])
cs_publish(list(
method = "describe.semantic_search",
methodVersion = "1.1.0",
title = "Semantic search",
engine = cs_engine_info("nanoparquet", "stringi"),
n = n,
summary = summary,
statistics = c(list(list(key = "n_docs", label = "Texts", value = n), list(key = "n_queries", label = "Queries", value = m)),
if (!is.na(n_terms)) list(list(key = "n_terms", label = "Distinct words (BM25)", value = n_terms)) else list()),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = if (!is.null(bm25)) list("BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.") else list(),
charts = charts,
values = values
))
3 queries over 61 texts by words (BM25); best match for query 1: row 1.
- Texts
- 61
- Queries
- 3
- Distinct words (BM25)
- 231
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Words or meaning — BM25 matches shared words only; texts that use other words for the same idea score 0.
- English text — The stop list and all-MiniLM-L6-v2 are English.
Best-ranked texts
| Query | Query text | Rank | Row | doc | Text | BM25 score |
|---|---|---|---|---|---|---|
| 1 | late goal in the match | 1 | 1 | d01 | The striker scored a late goal and the team won the match at home | 7.521 |
| 1 | late goal in the match | 2 | 12 | d12 | League rivals met in a tense match that ended with a late goal | 7.521 |
| 1 | late goal in the match | 3 | 7 | d07 | The referee awarded a penalty and the striker scored the winning goal | 2.797 |
| 1 | late goal in the match | 4 | 19 | d19 | Training focused on set pieces before the derby match | 2.188 |
| 1 | late goal in the match | 5 | 3 | d03 | The coach praised the defence after a clean sheet in the league match | 2.055 |
| 2 | bake bread with flour and butter | 1 | 36 | d36 | Slice the bread and serve it warm with butter and soup | 6.653 |
| 2 | bake bread with flour and butter | 2 | 27 | d27 | Bake the bread until the crust is golden and sounds hollow | 6.044 |
| 2 | bake bread with flour and butter | 3 | 28 | d28 | Whisk the eggs with sugar then fold in the flour gently | 3.856 |
| 2 | bake bread with flour and butter | 4 | 31 | d31 | Fry the fish in butter and finish it with lemon and herbs | 3.327 |
| 2 | bake bread with flour and butter | 5 | 32 | d32 | Let the dough rest before you roll it out and bake it | 2.905 |
| 3 | interest rates | 1 | 50 | d50 | The currency weakened after the bank cut interest rates | 4.028 |
| 3 | interest rates | 2 | 41 | d41 | Shares fell as investors worried about rising interest rates | 3.784 |
| 3 | interest rates | 3 | 42 | d42 | The central bank raised interest rates to slow inflation | 3.784 |
| 3 | interest rates | 4 | 46 | d46 | Inflation eased and the bank signalled lower interest rates | 3.784 |
| 3 | interest rates | 5 | 57 | d57 | The fund manager bought bonds as interest rates peaked | 3.784 |
Ties keep row order.
Queries
| Query | Text |
|---|---|
| 1 | late goal in the match |
| 2 | bake bread with flour and butter |
| 3 | interest rates |
- 1 of 62 rows were left out because a value was missing.
- BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Semantic search (BM25, sentence embeddings, hybrid)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.semantic_search 1.1.0 · spec 611d7166eac896fa
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.text import search as ss # BM25, rankings, rank fusion (twin: codesplashr cs_bm25*, cs_search_*)
# %% Data (rows with a text)
TEXT = "text"
LABEL = "doc"
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=["text", "doc"])
n_input = len(df)
df = df[df[TEXT].notna()]
warnings = []
if n_input - len(df):
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
rows = (df.index.to_numpy() + 1).astype(np.int64) # 1-based input rows
texts = df[TEXT].astype(str).tolist()
n = len(texts)
names = [None if pd.isna(v) else str(v) for v in df[LABEL].tolist()] if LABEL else [None] * n
unique_names = LABEL is not None and None not in names and len(set(names)) == n
doc_label = [names[i] if unique_names else f"Row {rows[i]}" for i in range(n)]
# %% Queries and settings
QUERIES = ss.split_list("late goal in the match; bake bread with flour and butter; interest rates")
if not QUERIES:
cs.cs_error("CS_E_INVALID_OPTION", option="Queries", allowed="at least one query (separate several with semicolons)", value="(empty)")
if len(QUERIES) > 50:
cs.cs_error("CS_E_INVALID_OPTION", option="Queries", allowed="at most 50 queries", value=f"{len(QUERIES)} queries")
RETRIEVER = "bm25"
TOP_K = min(int(5), n)
m = len(QUERIES)
# %% Scores
bm25 = dense = None
n_terms, no_match = None, []
if RETRIEVER in ("bm25", "hybrid"):
bm = ss.Bm25(texts, k1=1.2, b=0.75)
if bm.avgdl <= 0:
cs.cs_error("CS_E_UNDEFINED", what="BM25 scores", reason="no text has a word of two or more letters outside the common-word list")
n_terms = bm.n_terms
bm25 = np.vstack([bm.scores(q) for q in QUERIES]) # queries × texts
no_match = [j for j in range(m) if not np.any(bm25[j] > 0)]
for j in no_match:
warnings.append(f"Query {j + 1} (“{ss.snippet(QUERIES[j], 40)}”) shares no word with any text, so its BM25 ranking is just row order.")
if RETRIEVER in ("dense", "hybrid"):
from codesplash.text import minilm # all-MiniLM-L6-v2 in numpy (twin: cs_minilm_embed)
if not minilm.available():
cs.cs_error("CS_WEIGHTS_MISSING", model=f"{minilm.NAME} (download it from Discover → Topics in text → Pretrained embeddings)")
model = minilm.Model()
dense = ss.cosine(minilm.embed(QUERIES, model), minilm.embed(texts, model)) # queries × texts
if RETRIEVER == "bm25":
final = bm25
elif RETRIEVER == "dense":
final = dense
else:
final = np.vstack([ss.rrf(ss.ranks(bm25[j]), ss.ranks(dense[j]), k=60) for j in range(m)])
# %% Rankings
result_rows = []
values = {"n_docs": n, "n_queries": m, "top_k": TOP_K,
"retriever": {"bm25": "words (BM25)", "dense": "meaning (sentence embeddings)", "hybrid": "words and meaning (reciprocal rank fusion)"}[RETRIEVER],
"n_terms": n_terms, "n_no_match": len(no_match) if bm25 is not None else None}
for j, q in enumerate(QUERIES):
order = ss.ranking(final[j])[:TOP_K]
key = f"q{j + 1}"
values[f"top_row[{key}]"] = int(rows[order[0]])
values[f"top_score[{key}]"] = float(final[j][order[0]])
for r, i in enumerate(order, start=1):
values[f"row[{key}:{r}]"] = int(rows[i])
values[f"score[{key}:{r}]"] = float(final[j][i])
row = {"query": j + 1, "query_text": ss.snippet(q, 60), "rank": r, "row": int(rows[i]), "document": doc_label[i],
"text": ss.snippet(texts[i]), "score": float(final[j][i])}
if RETRIEVER == "hybrid":
row["bm25"] = float(bm25[j][i])
row["similarity"] = float(dense[j][i])
result_rows.append(row)
score_label = {"bm25": "BM25 score", "dense": "Cosine similarity", "hybrid": "Fusion score"}[RETRIEVER]
cols = [{"key": "query", "label": "Query", "type": "integer"}, {"key": "query_text", "label": "Query text", "type": "string"},
{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"}]
if LABEL:
cols.append({"key": "document", "label": LABEL if unique_names else "Document", "type": "string"})
cols += [{"key": "text", "label": "Text", "type": "string"}, {"key": "score", "label": score_label, "type": "number"}]
if RETRIEVER == "hybrid":
cols += [{"key": "bm25", "label": "BM25 score", "type": "number"}, {"key": "similarity", "label": "Cosine similarity", "type": "number"}]
tables = [
{"key": "results", "title": "Best-ranked texts", "columns": cols, "rows": result_rows,
"note": "Ties keep row order." + (" Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings." if RETRIEVER == "hybrid" else "")},
{"key": "queries", "title": "Queries", "columns": [{"key": "query", "label": "Query", "type": "integer"}, {"key": "text", "label": "Text", "type": "string"}],
"rows": [{"query": j + 1, "text": q} for j, q in enumerate(QUERIES)]},
]
charts = []
if m <= 9: # the chart draws at most 9 panels; the table has every query
qlevels = [f"Q{j + 1}" for j in range(m)]
terms, scores, groups = [], [], []
for res in result_rows:
terms.append(res["document"])
scores.append(res["score"])
groups.append(f"Q{res['query']}")
charts.append(cs.chart("results", "ngram-bars", f"Best-ranked texts per query ({score_label.lower()})", {
"term": cs.col("Text", terms, kind="categorical"), "count": cs.col(score_label, scores),
"group": cs.col("Query", groups, kind="categorical", levels=qlevels)}, controls={"top": max(3, TOP_K)}))
assumptions = [
{"key": "words_vs_meaning", "label": "Words or meaning", "status": "info",
"detail": {"bm25": "BM25 matches shared words only; texts that use other words for the same idea score 0.",
"dense": "Dense search matches meaning; exact names, numbers and codes can rank lower than with BM25.",
"hybrid": "Hybrid search combines both rankings, so a text matched by words or by meaning can rise."}[RETRIEVER]},
{"key": "language", "label": "English text", "status": "info", "detail": "The stop list and all-MiniLM-L6-v2 are English."},
]
summary = f"{m} quer{'y' if m == 1 else 'ies'} over {n} texts by {values['retriever']}; best match for query 1: row {values['top_row[q1]']}."
cs.publish({
"method": "describe.semantic_search",
"methodVersion": "1.1.0",
"title": "Semantic search",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [{"key": "n_docs", "label": "Texts", "value": n}, {"key": "n_queries", "label": "Queries", "value": m}]
+ ([{"key": "n_terms", "label": "Distinct words (BM25)", "value": n_terms}] if n_terms is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": ["BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out."] if bm25 is not None else [],
"charts": charts,
"values": values,
})
Type your own queries, separated by semicolons. Then switch Search by to meaning and to both, and see which texts move.
Fusing two rankings
ReadHybrid search uses reciprocal rank fusionReciprocal rank fusion (RRF)Combines rankings by adding 1 / (k + rank) from each; a text ranked well by any list rises, and raw scores never need rescaling.. Each text earns 1 / (k + rank) from the BM25 ranking and again from the dense ranking. A text near the top of either list rises, and BM25 scores never have to be put on the same scale as cosines. With k = 20, the best fusion score for the first query here is 0.0931.
View data
| bigram | count | rating |
|---|---|---|
| late delivery | 62 | 1–2 stars |
| refund | 50 | 1–2 stars |
| customer service | 45 | 1–2 stars |
| broken | 39 | 1–2 stars |
| never arrived | 33 | 1–2 stars |
| waste | 25 | 1–2 stars |
| wrong size | 25 | 1–2 stars |
| poor quality | 24 | 1–2 stars |
| support | 18 | 1–2 stars |
| return | 18 | 1–2 stars |
| great quality | 74 | 4–5 stars |
| fast shipping | 60 | 4–5 stars |
| love | 52 | 4–5 stars |
| fits perfectly | 38 | 4–5 stars |
| easy | 35 | 4–5 stars |
| recommend | 33 | 4–5 stars |
| comfortable | 31 | 4–5 stars |
| good value | 26 | 4–5 stars |
| gift | 16 | 4–5 stars |
| soft | 17 | 4–5 stars |
Labels without training
ReadSometimes you know the categories but have no labeled examples. Zero-shot labels writes each label into a sentence ("This text is about sport.") and gives each text the label it is most similar to.
On the same column, with the labels sport, cooking and finance, 100.0% of the 61 texts with a known theme got the right label (macro F1 1.00).
61 texts into 3 labels; most common finance (34%); accuracy 100% against theme.
- Texts
- 61
- Labels
- 3
- Mean margin
- 0.2229
- Accuracy
- 100.0%
- Macro F1
- 1
Plots
View data
| Texts | Label |
|---|---|
| 20 | sport |
| 20 | cooking |
| 21 | finance |
View data
| Margin |
|---|
| 0.1220 |
| 0.1145 |
| 0.1360 |
| 0.1915 |
| 0.2859 |
| 0.1832 |
| 0.1199 |
| 0.2201 |
| 0.1541 |
| 0.1751 |
| 0.0527 |
| 0.2158 |
| 0.2230 |
| 0.1561 |
| 0.1873 |
| 0.0087 |
| 0.2549 |
| 0.1449 |
| 0.2370 |
| 0.0558 |
| 0.2842 |
| 0.3200 |
| 0.2824 |
| 0.2003 |
| 0.3854 |
| 0.3380 |
| 0.3283 |
| 0.2248 |
| 0.3520 |
| 0.2702 |
| 0.2749 |
| 0.2520 |
| 0.1756 |
| 0.2778 |
| 0.3419 |
| 0.3104 |
| 0.2773 |
| 0.2662 |
| 0.2431 |
| 0.3681 |
| 0.2081 |
| 0.2676 |
| 0.1135 |
| 0.2104 |
| 0.2483 |
| 0.2883 |
| 0.1367 |
| 0.1742 |
| 0.3109 |
| 0.2776 |
| 0.2029 |
| 0.2837 |
| 0.1654 |
| 0.2936 |
| 0.1464 |
| 0.2009 |
| 0.2805 |
| 0.2096 |
| 0.2340 |
| 0.2634 |
First 60 of 61 rows.
View data
| theme | Zero-shot label |
|---|---|
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
First 60 of 61 rows.
Assumptions
- Label wording — Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result.
- English text — all-MiniLM-L6-v2 was trained mostly on English text.
- No training on your labels — No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better.
Labels
| Label | Texts | Share of texts | Mean similarity (labeled texts) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| sport | 20 | 0.3279 | 0.2096 | 20 | 1 | 1 | 1 |
| cooking | 20 | 0.3279 | 0.2793 | 20 | 1 | 1 | 1 |
| finance | 21 | 0.3443 | 0.2501 | 21 | 1 | 1 | 1 |
Each label is embedded as “This text is about {label}.” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings.
Labeled texts
| Row | Text | Label | Similarity | Margin to the next label | Known label |
|---|---|---|---|---|---|
| 1 | The striker scored a late goal and the team won the match at home | sport | 0.1728 | 0.1220 | sport |
| 2 | Fans cheered as the goalkeeper saved a penalty in the final minute | sport | 0.1481 | 0.1145 | sport |
| 3 | The coach praised the defence after a clean sheet in the league match | sport | 0.2232 | 0.1360 | sport |
| 4 | A thrilling match ended level after the striker hit the post twice | sport | 0.2325 | 0.1915 | sport |
| 5 | The team trained hard before the cup final against their rivals | sport | 0.3205 | 0.2859 | sport |
| 6 | Injury kept the captain out of the match but the team still won | sport | 0.2095 | 0.1832 | sport |
| 7 | The referee awarded a penalty and the striker scored the winning goal | sport | 0.1583 | 0.1199 | sport |
| 8 | Supporters filled the stadium to watch the league leaders play | sport | 0.1603 | 0.2201 | sport |
| 9 | The young winger crossed the ball and the striker headed it home | sport | 0.2143 | 0.1541 | sport |
| 10 | After the final whistle the coach thanked the fans for their support | sport | 0.2287 | 0.1751 | sport |
| 11 | The goalkeeper made three saves to keep the team in the cup | sport | 0.1491 | 0.0527 | sport |
| 12 | League rivals met in a tense match that ended with a late goal | sport | 0.2235 | 0.2158 | sport |
| 13 | The team celebrated the title with their fans in the stadium | sport | 0.2024 | 0.2230 | sport |
| 14 | A penalty miss cost the team the match against the league leaders | sport | 0.2213 | 0.1561 | sport |
| 15 | The coach changed the formation and the team pressed higher | sport | 0.3136 | 0.1873 | sport |
| 16 | The striker signed a new contract after a season of goals | sport | 0.0787 | 0.0087 | sport |
| 17 | Rain made the pitch heavy but the team kept passing the ball | sport | 0.2617 | 0.2549 | sport |
| 18 | The captain lifted the cup as fans sang in the stadium | sport | 0.1740 | 0.1449 | sport |
| 19 | Training focused on set pieces before the derby match | sport | 0.3078 | 0.2370 | sport |
| 20 | The defence held firm and the goalkeeper kept another clean sheet | sport | 0.1925 | 0.0558 | sport |
| 21 | Chop the onions and garlic then fry them gently in olive oil | cooking | 0.2388 | 0.2842 | cooking |
| 22 | Add the tomatoes and simmer the sauce for twenty minutes | cooking | 0.2932 | 0.3200 | cooking |
| 23 | Season the soup with salt and pepper before serving it hot | cooking | 0.3172 | 0.2824 | cooking |
| 24 | Knead the dough until smooth and let it rise in a warm place | cooking | 0.1870 | 0.2003 | cooking |
| 25 | Roast the vegetables with olive oil garlic and fresh herbs | cooking | 0.3406 | 0.3854 | cooking |
| 26 | Stir the sauce often so the garlic and onions do not burn | cooking | 0.3031 | 0.3380 | cooking |
| 27 | Bake the bread until the crust is golden and sounds hollow | cooking | 0.3117 | 0.3283 | cooking |
| 28 | Whisk the eggs with sugar then fold in the flour gently | cooking | 0.1901 | 0.2248 | cooking |
| 29 | Simmer the beans with tomatoes onions and a pinch of salt | cooking | 0.3026 | 0.3520 | cooking |
| 30 | Serve the pasta with the tomato sauce and fresh basil | cooking | 0.3015 | 0.2702 | cooking |
| 31 | Fry the fish in butter and finish it with lemon and herbs | cooking | 0.2904 | 0.2749 | cooking |
| 32 | Let the dough rest before you roll it out and bake it | cooking | 0.2383 | 0.2520 | cooking |
| 33 | Add stock to the pan and simmer the rice until tender | cooking | 0.2937 | 0.1756 | cooking |
| 34 | Grate the cheese over the pasta and bake until bubbling | cooking | 0.2915 | 0.2778 | cooking |
| 35 | Toast the spices in a dry pan before adding the onions | cooking | 0.2815 | 0.3419 | cooking |
| 36 | Slice the bread and serve it warm with butter and soup | cooking | 0.3423 | 0.3104 | cooking |
| 37 | Marinate the chicken with garlic lemon and olive oil overnight | cooking | 0.2304 | 0.2773 | cooking |
| 38 | Taste the sauce and add salt pepper or a little sugar | cooking | 0.2589 | 0.2662 | cooking |
| 39 | Bake the cake for forty minutes and let it cool on a rack | cooking | 0.2558 | 0.2431 | cooking |
| 40 | Roast the chicken with garlic herbs and lemon until golden | cooking | 0.3173 | 0.3681 | cooking |
First 40 of 61 rows.
- 1 of 62 rows were left out because a value was missing.
- Labels are probabilities from a softmax of similarity ÷ 0.05; the predicted label is the most similar one (ties go to the label listed first).
The exact R script · R R version 4.5.1 (2025-06-13)
# Zero-shot text labels (sentence embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.zero_shot_text 1.0.0 · spec 52703ebb414de8c7
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_minilm_embed (all-MiniLM-L6-v2 in base R) and cs_zero_shot* (twins of codesplash.text.search)
# %% Data (rows with a text; known labels may be missing)
TEXT <- "text"
TRUTH <- "theme"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c("text", "theme")))
n_input <- nrow(df)
keep_rows <- which(!is.na(df[[TEXT]]))
df <- df[keep_rows, , drop = FALSE]
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
rows <- as.integer(keep_rows) # 1-based input rows
texts <- as.character(df[[TEXT]])
n <- length(texts)
truth <- as.character(df[[TRUTH]])
seen <- unique(truth[!is.na(truth)])
truth_levels <- intersect(c("cooking", "finance", "sport"), seen) # stored level order
# %% Labels
LABELS <- cs_search_split_labels("sport, cooking, finance")
if (!length(LABELS) && length(truth_levels)) LABELS <- truth_levels
if (length(LABELS) < 2) {
cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "at least two labels separated by commas",
value = if (length(LABELS)) paste(LABELS, collapse = ", ") else "(empty)")
}
if (anyDuplicated(LABELS)) cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "distinct labels", value = paste(LABELS, collapse = ", "))
TEMPLATE <- "This text is about {label}."
if (!grepl("{label}", TEMPLATE, fixed = TRUE)) cs_error("CS_E_INVALID_OPTION", option = "Label sentence", allowed = "a sentence containing {label}", value = TEMPLATE)
MIN_SIM <- NULL
TEMPERATURE <- 0.05
L <- length(LABELS)
# %% Embeddings and similarities
EMBEDDER <- "minilm" # "minilm": all-MiniLM-L6-v2, the only embedder today
if (!cs_minilm_available()) cs_error("CS_WEIGHTS_MISSING", model = "all-MiniLM-L6-v2 (download it from Discover → Topics in text → Pretrained embeddings)")
model <- cs_minilm_load()
E_text <- cs_minilm_embed(texts, model) # n x 384, unit rows
E_label <- cs_minilm_embed(cs_zero_shot_prompts(LABELS, TEMPLATE), model)
sim <- cs_search_cosine(E_text, E_label) # texts x labels
z <- cs_zero_shot(sim, TEMPERATURE)
assigned <- if (is.null(MIN_SIM)) rep(TRUE, n) else z$best >= MIN_SIM
pred <- ifelse(assigned, LABELS[z$pred], NA_character_)
n_unassigned <- sum(!assigned)
# %% Agreement with the known labels
ev <- NULL
n_not_in <- 0L
if (!is.null(truth)) {
keep <- which(!is.na(truth) & truth %in% LABELS)
n_not_in <- sum(!is.na(truth) & !(truth %in% LABELS))
if (n_not_in > 0) warnings <- c(warnings, sprintf("%d known label(s) are not among the labels and are left out of the agreement figures.", n_not_in))
if (length(keep)) {
ev <- cs_zero_shot_classification(truth[keep], pred[keep], LABELS)
} else {
warnings <- c(warnings, "No text has a known label that is one of the labels, so agreement can't be computed.")
}
}
# %% Result
counts <- vapply(LABELS, function(l) sum(!is.na(pred) & pred == l), numeric(1), USE.NAMES = FALSE)
names(counts) <- LABELS
mean_sim <- lapply(LABELS, function(l) { m <- !is.na(pred) & pred == l; if (any(m)) mean(z$best[m]) else NA })
names(mean_sim) <- LABELS
never <- LABELS[counts == 0]
if (length(never)) warnings <- c(warnings, sprintf("No text was given %s.", paste(never, collapse = ", ")))
if (n_unassigned > 0) warnings <- c(warnings, sprintf("%d text(s) have no label above the minimum similarity %s.", n_unassigned, format(MIN_SIM, digits = 6)))
values <- list(
n_docs = n, n_labels = L, embedder = "all-MiniLM-L6-v2", labels_text = paste(LABELS, collapse = ", "),
mean_best = mean(z$best), mean_margin = mean(z$margin),
n_unassigned = n_unassigned, coverage = 1 - n_unassigned / n,
n_evaluated = if (!is.null(ev)) ev$n else if (!is.null(truth)) 0L else NA,
n_not_in_labels = if (!is.null(truth)) n_not_in else NA,
accuracy = if (!is.null(ev)) ev$accuracy else NA, macro_f1 = if (!is.null(ev)) ev$macro_f1 else NA,
balanced_accuracy = if (!is.null(ev)) ev$balanced_accuracy else NA
)
for (l in LABELS) {
values[[sprintf("n[%s]", l)]] <- counts[[l]]
values[[sprintf("share[%s]", l)]] <- counts[[l]] / n
values[[sprintf("mean_similarity[%s]", l)]] <- mean_sim[[l]]
}
if (!is.null(ev)) for (r in ev$rows) values[[sprintf("f1[%s]", r$label)]] <- r$f1
label_cols <- list(list(key = "label", label = "Label", type = "string"), list(key = "texts", label = "Texts", type = "integer"),
list(key = "share", label = "Share of texts", type = "number"), list(key = "similarity", label = "Mean similarity (labeled texts)", type = "number"))
label_rows <- lapply(LABELS, function(l) list(label = l, texts = counts[[l]], share = counts[[l]] / n, similarity = mean_sim[[l]]))
if (!is.null(ev)) {
label_cols <- c(label_cols, list(list(key = "support", label = "Known", type = "integer"), list(key = "precision", label = "Precision", type = "number"),
list(key = "recall", label = "Recall", type = "number"), list(key = "f1", label = "F1", type = "number")))
for (j in seq_along(label_rows)) {
r <- ev$rows[[j]]
label_rows[[j]] <- c(label_rows[[j]], list(support = r$support, precision = r$precision, recall = r$recall, f1 = r$f1))
}
}
SHOW <- min(n, 100L)
pred_cols <- list(list(key = "row", label = "Row", type = "integer"), list(key = "text", label = "Text", type = "string"),
list(key = "label", label = "Label", type = "string"), list(key = "similarity", label = "Similarity", type = "number"),
list(key = "margin", label = "Margin to the next label", type = "number"))
if (!is.null(truth)) pred_cols <- c(pred_cols, list(list(key = "known", label = "Known label", type = "string")))
pred_rows <- lapply(seq_len(SHOW), function(i) {
r <- list(row = rows[i], text = cs_search_snippet(texts[i]), label = pred[i], similarity = z$best[i], margin = z$margin[i])
if (!is.null(truth)) r$known <- truth[i]
r
})
tables <- list(
list(key = "labels", title = "Labels", columns = label_cols, rows = label_rows,
note = sprintf("Each label is embedded as “%s” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings.", TEMPLATE)),
list(key = "texts", title = "Labeled texts", columns = pred_cols, rows = pred_rows,
note = if (SHOW == n) NULL else sprintf("The first %d of %d texts.", SHOW, n))
)
charts <- list(
cs_chart("labels", "ngram-bars", "Texts per label",
list(term = cs_col("Label", LABELS, kind = "categorical"), count = cs_col("Texts", unname(counts))), controls = list(top = min(L, 50L))),
cs_chart("margins", "histogram", "Margin between the best and the second-best label", list(x = cs_col("Margin", z$margin)))
)
if (!is.null(ev)) {
keep <- which(!is.na(truth) & truth %in% LABELS)
levels_pred <- c(LABELS, if (any(is.na(pred[keep]))) "(no label)")
charts[[length(charts) + 1]] <- cs_chart("confusion", "confusion-matrix", sprintf("Zero-shot labels against %s", TRUTH),
list(actual = cs_col(TRUTH, truth[keep], kind = "categorical", levels = LABELS),
predicted = cs_col("Zero-shot label", ifelse(is.na(pred[keep]), "(no label)", pred[keep]), kind = "categorical", levels = levels_pred)))
}
statistics <- list(list(key = "n_docs", label = "Texts", value = n), list(key = "n_labels", label = "Labels", value = L),
list(key = "mean_margin", label = "Mean margin", value = values$mean_margin))
if (!is.null(ev)) statistics <- c(statistics, list(list(key = "accuracy", label = "Accuracy", value = values$accuracy, format = "percent"),
list(key = "macro_f1", label = "Macro F1", value = values$macro_f1)))
assumptions <- list(
list(key = "wording", label = "Label wording", status = "info",
detail = "Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result."),
list(key = "language", label = "English text", status = "info", detail = "all-MiniLM-L6-v2 was trained mostly on English text."),
list(key = "not_trained", label = "No training on your labels", status = "info",
detail = "No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better.")
)
top <- LABELS[which.max(counts)]
summary <- paste0(sprintf("%d texts into %d labels; most common %s (%s)", n, L, top, sprintf("%.0f%%", 100 * counts[[top]] / n)),
if (!is.null(ev)) sprintf("; accuracy %.0f%% against %s.", 100 * values$accuracy, TRUTH) else ".")
cs_publish(list(
method = "describe.zero_shot_text",
methodVersion = "1.0.0",
title = "Zero-shot text labels",
engine = cs_engine_info("nanoparquet", "stringi"),
n = n,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Labels are probabilities from a softmax of similarity ÷ %s; the predicted label is the most similar one (ties go to the label listed first).", format(TEMPERATURE, digits = 6))),
charts = charts,
values = values
))
61 texts into 3 labels; most common finance (34%); accuracy 100% against theme.
- Texts
- 61
- Labels
- 3
- Mean margin
- 0.2229
- Accuracy
- 100.0%
- Macro F1
- 1
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Label wording — Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result.
- English text — all-MiniLM-L6-v2 was trained mostly on English text.
- No training on your labels — No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better.
Labels
| Label | Texts | Share of texts | Mean similarity (labeled texts) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| sport | 20 | 0.3279 | 0.2096 | 20 | 1 | 1 | 1 |
| cooking | 20 | 0.3279 | 0.2793 | 20 | 1 | 1 | 1 |
| finance | 21 | 0.3443 | 0.2501 | 21 | 1 | 1 | 1 |
Each label is embedded as “This text is about {label}.” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings.
Labeled texts
| Row | Text | Label | Similarity | Margin to the next label | Known label |
|---|---|---|---|---|---|
| 1 | The striker scored a late goal and the team won the match at home | sport | 0.1728 | 0.1220 | sport |
| 2 | Fans cheered as the goalkeeper saved a penalty in the final minute | sport | 0.1481 | 0.1145 | sport |
| 3 | The coach praised the defence after a clean sheet in the league match | sport | 0.2232 | 0.1360 | sport |
| 4 | A thrilling match ended level after the striker hit the post twice | sport | 0.2325 | 0.1915 | sport |
| 5 | The team trained hard before the cup final against their rivals | sport | 0.3205 | 0.2859 | sport |
| 6 | Injury kept the captain out of the match but the team still won | sport | 0.2095 | 0.1832 | sport |
| 7 | The referee awarded a penalty and the striker scored the winning goal | sport | 0.1583 | 0.1199 | sport |
| 8 | Supporters filled the stadium to watch the league leaders play | sport | 0.1603 | 0.2201 | sport |
| 9 | The young winger crossed the ball and the striker headed it home | sport | 0.2143 | 0.1541 | sport |
| 10 | After the final whistle the coach thanked the fans for their support | sport | 0.2287 | 0.1751 | sport |
| 11 | The goalkeeper made three saves to keep the team in the cup | sport | 0.1491 | 0.0527 | sport |
| 12 | League rivals met in a tense match that ended with a late goal | sport | 0.2235 | 0.2158 | sport |
| 13 | The team celebrated the title with their fans in the stadium | sport | 0.2024 | 0.2230 | sport |
| 14 | A penalty miss cost the team the match against the league leaders | sport | 0.2213 | 0.1561 | sport |
| 15 | The coach changed the formation and the team pressed higher | sport | 0.3136 | 0.1873 | sport |
| 16 | The striker signed a new contract after a season of goals | sport | 0.0787 | 0.0087 | sport |
| 17 | Rain made the pitch heavy but the team kept passing the ball | sport | 0.2617 | 0.2549 | sport |
| 18 | The captain lifted the cup as fans sang in the stadium | sport | 0.1740 | 0.1449 | sport |
| 19 | Training focused on set pieces before the derby match | sport | 0.3078 | 0.2370 | sport |
| 20 | The defence held firm and the goalkeeper kept another clean sheet | sport | 0.1925 | 0.0558 | sport |
| 21 | Chop the onions and garlic then fry them gently in olive oil | cooking | 0.2388 | 0.2842 | cooking |
| 22 | Add the tomatoes and simmer the sauce for twenty minutes | cooking | 0.2932 | 0.3200 | cooking |
| 23 | Season the soup with salt and pepper before serving it hot | cooking | 0.3172 | 0.2824 | cooking |
| 24 | Knead the dough until smooth and let it rise in a warm place | cooking | 0.1870 | 0.2003 | cooking |
| 25 | Roast the vegetables with olive oil garlic and fresh herbs | cooking | 0.3406 | 0.3854 | cooking |
| 26 | Stir the sauce often so the garlic and onions do not burn | cooking | 0.3031 | 0.3380 | cooking |
| 27 | Bake the bread until the crust is golden and sounds hollow | cooking | 0.3117 | 0.3283 | cooking |
| 28 | Whisk the eggs with sugar then fold in the flour gently | cooking | 0.1901 | 0.2248 | cooking |
| 29 | Simmer the beans with tomatoes onions and a pinch of salt | cooking | 0.3026 | 0.3520 | cooking |
| 30 | Serve the pasta with the tomato sauce and fresh basil | cooking | 0.3015 | 0.2702 | cooking |
| 31 | Fry the fish in butter and finish it with lemon and herbs | cooking | 0.2904 | 0.2749 | cooking |
| 32 | Let the dough rest before you roll it out and bake it | cooking | 0.2383 | 0.2520 | cooking |
| 33 | Add stock to the pan and simmer the rice until tender | cooking | 0.2937 | 0.1756 | cooking |
| 34 | Grate the cheese over the pasta and bake until bubbling | cooking | 0.2915 | 0.2778 | cooking |
| 35 | Toast the spices in a dry pan before adding the onions | cooking | 0.2815 | 0.3419 | cooking |
| 36 | Slice the bread and serve it warm with butter and soup | cooking | 0.3423 | 0.3104 | cooking |
| 37 | Marinate the chicken with garlic lemon and olive oil overnight | cooking | 0.2304 | 0.2773 | cooking |
| 38 | Taste the sauce and add salt pepper or a little sugar | cooking | 0.2589 | 0.2662 | cooking |
| 39 | Bake the cake for forty minutes and let it cool on a rack | cooking | 0.2558 | 0.2431 | cooking |
| 40 | Roast the chicken with garlic herbs and lemon until golden | cooking | 0.3173 | 0.3681 | cooking |
First 40 of 61 rows.
- 1 of 62 rows were left out because a value was missing.
- Labels are probabilities from a softmax of similarity ÷ 0.05; the predicted label is the most similar one (ties go to the label listed first).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Zero-shot text labels (sentence embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.zero_shot_text 1.0.0 · spec 52703ebb414de8c7
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.text import minilm # all-MiniLM-L6-v2 in numpy (twin: codesplashr cs_minilm_embed)
from codesplash.text import search as zs # labels, cosine, first-maximum labels, metrics (twin: cs_zero_shot*)
# %% Data (rows with a text; known labels may be missing)
TEXT = "text"
TRUTH = "theme"
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=["text", "theme"])
n_input = len(df)
df = df[df[TEXT].notna()]
warnings = []
if n_input - len(df):
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
rows = (df.index.to_numpy() + 1).astype(np.int64) # 1-based input rows
texts = df[TEXT].astype(str).tolist()
n = len(texts)
truth = [None if pd.isna(v) else str(v) for v in df[TRUTH].tolist()]
truth_levels = [lv for lv in ["cooking", "finance", "sport"] if lv in set(t for t in truth if t is not None)] # stored level order
# %% Labels
LABELS = zs.split_labels("sport, cooking, finance")
if not LABELS and truth_levels:
LABELS = list(truth_levels)
if len(LABELS) < 2:
cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="at least two labels separated by commas", value=", ".join(LABELS) or "(empty)")
if len(set(LABELS)) < len(LABELS):
cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="distinct labels", value=", ".join(LABELS))
TEMPLATE = "This text is about {label}."
if zs.LABEL_SLOT not in TEMPLATE:
cs.cs_error("CS_E_INVALID_OPTION", option="Label sentence", allowed="a sentence containing {label}", value=TEMPLATE)
MIN_SIM = None
TEMPERATURE = 0.05
L = len(LABELS)
# %% Embeddings and similarities
EMBEDDER = "minilm" # "minilm": all-MiniLM-L6-v2, the only embedder today
if not minilm.available():
cs.cs_error("CS_WEIGHTS_MISSING", model=f"{minilm.NAME} (download it from Discover → Topics in text → Pretrained embeddings)")
model = minilm.Model()
E_text = minilm.embed(texts, model) # n × 384, unit rows
E_label = minilm.embed(zs.label_prompts(LABELS, TEMPLATE), model)
sim = zs.cosine(E_text, E_label) # texts × labels
z = zs.zero_shot(sim, TEMPERATURE)
assigned = np.ones(n, dtype=bool) if MIN_SIM is None else z["best"] >= MIN_SIM
pred = [LABELS[int(j)] if ok else None for j, ok in zip(z["pred"], assigned)]
n_unassigned = int(np.sum(~assigned))
# %% Agreement with the known labels
ev = None
n_not_in = 0
if truth is not None:
keep = [i for i, t in enumerate(truth) if t is not None and t in LABELS]
n_not_in = sum(1 for t in truth if t is not None and t not in LABELS)
if n_not_in:
warnings.append(f"{n_not_in} known label(s) are not among the labels and are left out of the agreement figures.")
if keep:
ev = zs.classification([truth[i] for i in keep], [pred[i] for i in keep], LABELS)
else:
warnings.append("No text has a known label that is one of the labels, so agreement can't be computed.")
# %% Result
counts = {lab: sum(1 for p in pred if p == lab) for lab in LABELS}
mean_sim = {}
for j, lab in enumerate(LABELS):
m = np.array([p == lab for p in pred])
mean_sim[lab] = float(z["best"][m].mean()) if m.any() else None
never = [lab for lab in LABELS if counts[lab] == 0]
if never:
warnings.append(f"No text was given {', '.join(never)}.")
if n_unassigned:
warnings.append(f"{n_unassigned} text(s) have no label above the minimum similarity {MIN_SIM:g}.")
values = {
"n_docs": n, "n_labels": L, "embedder": minilm.NAME, "labels_text": ", ".join(LABELS),
"mean_best": float(np.mean(z["best"])), "mean_margin": float(np.mean(z["margin"])),
"n_unassigned": n_unassigned, "coverage": 1.0 - n_unassigned / n,
"n_evaluated": ev["n"] if ev else (0 if truth is not None else None),
"n_not_in_labels": n_not_in if truth is not None else None,
"accuracy": ev["accuracy"] if ev else None, "macro_f1": ev["macro_f1"] if ev else None,
"balanced_accuracy": ev["balanced_accuracy"] if ev else None,
}
for lab in LABELS:
values[f"n[{lab}]"] = counts[lab]
values[f"share[{lab}]"] = counts[lab] / n
values[f"mean_similarity[{lab}]"] = mean_sim[lab]
if ev:
for r in ev["rows"]:
values[f"f1[{r['label']}]"] = r["f1"]
label_cols = [{"key": "label", "label": "Label", "type": "string"}, {"key": "texts", "label": "Texts", "type": "integer"},
{"key": "share", "label": "Share of texts", "type": "number"}, {"key": "similarity", "label": "Mean similarity (labeled texts)", "type": "number"}]
label_rows = [{"label": lab, "texts": counts[lab], "share": counts[lab] / n, "similarity": mean_sim[lab]} for lab in LABELS]
if ev:
label_cols += [{"key": "support", "label": "Known", "type": "integer"}, {"key": "precision", "label": "Precision", "type": "number"},
{"key": "recall", "label": "Recall", "type": "number"}, {"key": "f1", "label": "F1", "type": "number"}]
for row, r in zip(label_rows, ev["rows"]):
row.update({"support": r["support"], "precision": r["precision"], "recall": r["recall"], "f1": r["f1"]})
SHOW = min(n, 100)
pred_cols = [{"key": "row", "label": "Row", "type": "integer"}, {"key": "text", "label": "Text", "type": "string"},
{"key": "label", "label": "Label", "type": "string"}, {"key": "similarity", "label": "Similarity", "type": "number"},
{"key": "margin", "label": "Margin to the next label", "type": "number"}]
if truth is not None:
pred_cols.append({"key": "known", "label": "Known label", "type": "string"})
pred_rows = []
for i in range(SHOW):
r = {"row": int(rows[i]), "text": zs.snippet(texts[i]), "label": pred[i], "similarity": float(z["best"][i]), "margin": float(z["margin"][i])}
if truth is not None:
r["known"] = truth[i]
pred_rows.append(r)
tables = [
{"key": "labels", "title": "Labels", "columns": label_cols, "rows": label_rows,
"note": f"Each label is embedded as “{TEMPLATE}” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings."},
{"key": "texts", "title": "Labeled texts", "columns": pred_cols, "rows": pred_rows,
"note": None if SHOW == n else f"The first {SHOW} of {n} texts."},
]
charts = [
cs.chart("labels", "ngram-bars", "Texts per label", {
"term": cs.col("Label", LABELS, kind="categorical"), "count": cs.col("Texts", [counts[lab] for lab in LABELS])}, controls={"top": min(L, 50)}),
cs.chart("margins", "histogram", "Margin between the best and the second-best label", {"x": cs.col("Margin", z["margin"])}),
]
if ev:
keep = [i for i, t in enumerate(truth) if t is not None and t in LABELS]
levels_pred = LABELS + (["(no label)"] if any(pred[i] is None for i in keep) else [])
charts.append(cs.chart("confusion", "confusion-matrix", f"Zero-shot labels against {TRUTH}", {
"actual": cs.col(TRUTH, [truth[i] for i in keep], kind="categorical", levels=LABELS),
"predicted": cs.col("Zero-shot label", [pred[i] if pred[i] is not None else "(no label)" for i in keep], kind="categorical", levels=levels_pred)}))
statistics = [{"key": "n_docs", "label": "Texts", "value": n}, {"key": "n_labels", "label": "Labels", "value": L},
{"key": "mean_margin", "label": "Mean margin", "value": values["mean_margin"]}]
if ev:
statistics += [{"key": "accuracy", "label": "Accuracy", "value": values["accuracy"], "format": "percent"},
{"key": "macro_f1", "label": "Macro F1", "value": values["macro_f1"]}]
assumptions = [
{"key": "wording", "label": "Label wording", "status": "info",
"detail": "Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result."},
{"key": "language", "label": "English text", "status": "info", "detail": "all-MiniLM-L6-v2 was trained mostly on English text."},
{"key": "not_trained", "label": "No training on your labels", "status": "info",
"detail": "No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better."},
]
top = max(LABELS, key=lambda lab: (counts[lab], -LABELS.index(lab)))
summary = f"{n} texts into {L} labels; most common {top} ({counts[top] / n:.0%})" + (f"; accuracy {values['accuracy']:.0%} against {TRUTH}." if ev else ".")
cs.publish({
"method": "describe.zero_shot_text",
"methodVersion": "1.0.0",
"title": "Zero-shot text labels",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Labels are probabilities from a softmax of similarity ÷ {TEMPERATURE:g}; the predicted label is the most similar one (ties go to the label listed first)."],
"charts": charts,
"values": values,
})
Close calls
ReflectThe label marginLabel marginA text's similarity to its best label minus its similarity to the second best; small margins are close calls. is a text's similarity to its best label minus its similarity to the runner-up. On the product reviews, sorted into sound quality, battery life, comfort, price and delivery, the mean margin is 0.084. That's much smaller than on the clean themes (0.223).
Which reviews would you read first? Those with the smallest margins: they show where two labels overlap, or where a review is about something no label names.
View data
| churned | churn_probability |
|---|---|
| no | 0.1130 |
| no | 0.1960 |
| no | 0.0150 |
| no | 0.4510 |
| no | 0.0820 |
| no | 0.0180 |
| yes | 0.9500 |
| no | 0.5490 |
| no | 0.1550 |
| no | 0.5380 |
| no | 0.2070 |
| no | 0.1630 |
| no | 0.0720 |
| no | 0.4190 |
| yes | 0.8590 |
| no | 0.0530 |
| no | 0.2970 |
| no | 0.0430 |
| no | 0.0910 |
| no | 0.0760 |
| no | 0.0610 |
| no | 0.4490 |
| no | 0.0870 |
| no | 0.1210 |
| no | 0.0970 |
| no | 0.7310 |
| no | 0.3160 |
| no | 0.1260 |
| no | 0.1460 |
| no | 0.1380 |
| no | 0.0600 |
| no | 0.0700 |
| no | 0.0640 |
| no | 0.5060 |
| no | 0.7570 |
| no | 0.0910 |
| no | 0.0910 |
| no | 0.1450 |
| no | 0.0850 |
| yes | 0.9210 |
| yes | 0.9000 |
| no | 0.3470 |
| no | 0.1580 |
| no | 0.0060 |
| no | 0.0520 |
| no | 0.2120 |
| no | 0.2060 |
| no | 0.1880 |
| yes | 0.8940 |
| no | 0.5160 |
| no | 0.0660 |
| no | 0.0320 |
| yes | 0.8820 |
| no | 0.1710 |
| no | 0.6350 |
| no | 0.1400 |
| no | 0.1350 |
| no | 0.0600 |
| no | 0.4720 |
| no | 0.1760 |
First 60 of 1000 rows.
Check your understanding
CheckpointCheck yourself
You search support tickets for the error code "E-4021". Which search is the safer first choice?
Show the answer
Answer: a
Rare exact tokens are where word search is strongest. An embedding can place "E-4021" near other error codes and rank the wrong ticket first.
Check yourself
With k = 60, a text is ranked 1st by BM25 and 2nd by dense search. What's its reciprocal-rank-fusion score, to four decimals?
Show the answer
Answer: 0.0325
1 / (60 + 1) + 1 / (60 + 2) = 0.016393 + 0.016129 = 0.032522, which rounds to 0.0325.
Check yourself
Zero-shot labels put most complaints under "price". What's the best next step?
Show the answer
Answer: a
Zero-shot labels match by meaning, so the wording of the labels drives the result. The temperature only changes the probabilities, not which label wins.
Check yourself
Accuracy is 90%, but macro F1 is 0.55. What does that suggest?
Show the answer
Answer: a
Accuracy is dominated by the common labels. Macro F1 averages each label's F1, so a rare label that is usually missed pulls it down.
Recap
Recap- BM25 matches words and finds exact names; dense search matches meaning; hybrid fuses both rankings.
- A ranking says which texts match, not which are relevant: read the top results.
- Zero-shot labels need no training, but the label wording matters. Check them against known labels and read the close calls.
Concepts in this lesson