Skip to content

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.

Applied ~12 min8 steps

What runs in CodeSplash

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

01

Two ways to find a text

Read

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

02

Words versus meaning

Predict

Predict first

The query is "football game result". No text contains "football" or "game". Which search can still put the match reports first?

BM25Dense searchBoth equally
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.

03

Run it

In the app
Semantic searchRecorded · Python and R agreeRecorded 2026-11-25 · 42 values compared
R

3 queries over 61 texts by words (BM25); best match for query 1: row 1.

Texts
61
Queries
3
Distinct words (BM25)
231

Plots

Best-ranked texts per query (bm25 score)Which words or phrases appear most in a text column, overall or by group?
View data
BM25 scoreQueryText
7.521Q1d01
7.521Q1d12
2.797Q1d07
2.188Q1d19
2.055Q1d03
6.653Q2d36
6.044Q2d27
3.856Q2d28
3.327Q2d31
2.905Q2d32
4.028Q3d50
3.784Q3d41
3.784Q3d42
3.784Q3d46
3.784Q3d57

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

QueryQuery textRankRowdocTextBM25 score
1late goal in the match11d01The striker scored a late goal and the team won the match at home7.521
1late goal in the match212d12League rivals met in a tense match that ended with a late goal7.521
1late goal in the match37d07The referee awarded a penalty and the striker scored the winning goal2.797
1late goal in the match419d19Training focused on set pieces before the derby match2.188
1late goal in the match53d03The coach praised the defence after a clean sheet in the league match2.055
2bake bread with flour and butter136d36Slice the bread and serve it warm with butter and soup6.653
2bake bread with flour and butter227d27Bake the bread until the crust is golden and sounds hollow6.044
2bake bread with flour and butter328d28Whisk the eggs with sugar then fold in the flour gently3.856
2bake bread with flour and butter431d31Fry the fish in butter and finish it with lemon and herbs3.327
2bake bread with flour and butter532d32Let the dough rest before you roll it out and bake it2.905
3interest rates150d50The currency weakened after the bank cut interest rates4.028
3interest rates241d41Shares fell as investors worried about rising interest rates3.784
3interest rates342d42The central bank raised interest rates to slow inflation3.784
3interest rates446d46Inflation eased and the bank signalled lower interest rates3.784
3interest rates557d57The fund manager bought bonds as interest rates peaked3.784

Ties keep row order.

Queries

QueryText
1late goal in the match
2bake bread with flour and butter
3interest 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
))
Python

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

QueryQuery textRankRowdocTextBM25 score
1late goal in the match11d01The striker scored a late goal and the team won the match at home7.521
1late goal in the match212d12League rivals met in a tense match that ended with a late goal7.521
1late goal in the match37d07The referee awarded a penalty and the striker scored the winning goal2.797
1late goal in the match419d19Training focused on set pieces before the derby match2.188
1late goal in the match53d03The coach praised the defence after a clean sheet in the league match2.055
2bake bread with flour and butter136d36Slice the bread and serve it warm with butter and soup6.653
2bake bread with flour and butter227d27Bake the bread until the crust is golden and sounds hollow6.044
2bake bread with flour and butter328d28Whisk the eggs with sugar then fold in the flour gently3.856
2bake bread with flour and butter431d31Fry the fish in butter and finish it with lemon and herbs3.327
2bake bread with flour and butter532d32Let the dough rest before you roll it out and bake it2.905
3interest rates150d50The currency weakened after the bank cut interest rates4.028
3interest rates241d41Shares fell as investors worried about rising interest rates3.784
3interest rates342d42The central bank raised interest rates to slow inflation3.784
3interest rates446d46Inflation eased and the bank signalled lower interest rates3.784
3interest rates557d57The fund manager bought bonds as interest rates peaked3.784

Ties keep row order.

Queries

QueryText
1late goal in the match
2bake bread with flour and butter
3interest 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.

04

Fusing two rankings

Read

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

Top termsWhich words or phrases appear most in a text column, overall or by group?
View data
bigramcountrating
late delivery621–2 stars
refund501–2 stars
customer service451–2 stars
broken391–2 stars
never arrived331–2 stars
waste251–2 stars
wrong size251–2 stars
poor quality241–2 stars
support181–2 stars
return181–2 stars
great quality744–5 stars
fast shipping604–5 stars
love524–5 stars
fits perfectly384–5 stars
easy354–5 stars
recommend334–5 stars
comfortable314–5 stars
good value264–5 stars
gift164–5 stars
soft174–5 stars
05

Labels without training

Read

Sometimes 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).

Zero-shot text labelsRecorded · Python and R agreeRecorded 2026-11-21 · 25 values compared
R

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

Texts per labelWhich words or phrases appear most in a text column, overall or by group?
View data
TextsLabel
20sport
20cooking
21finance
Margin between the best and the second-best labelHow is one numeric variable distributed?
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.

Zero-shot labels against themeHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?
View data
themeZero-shot label
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance

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

LabelTextsShare of textsMean similarity (labeled texts)KnownPrecisionRecallF1
sport200.32790.209620111
cooking200.32790.279320111
finance210.34430.250121111

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

RowTextLabelSimilarityMargin to the next labelKnown label
1The striker scored a late goal and the team won the match at homesport0.17280.1220sport
2Fans cheered as the goalkeeper saved a penalty in the final minutesport0.14810.1145sport
3The coach praised the defence after a clean sheet in the league matchsport0.22320.1360sport
4A thrilling match ended level after the striker hit the post twicesport0.23250.1915sport
5The team trained hard before the cup final against their rivalssport0.32050.2859sport
6Injury kept the captain out of the match but the team still wonsport0.20950.1832sport
7The referee awarded a penalty and the striker scored the winning goalsport0.15830.1199sport
8Supporters filled the stadium to watch the league leaders playsport0.16030.2201sport
9The young winger crossed the ball and the striker headed it homesport0.21430.1541sport
10After the final whistle the coach thanked the fans for their supportsport0.22870.1751sport
11The goalkeeper made three saves to keep the team in the cupsport0.14910.0527sport
12League rivals met in a tense match that ended with a late goalsport0.22350.2158sport
13The team celebrated the title with their fans in the stadiumsport0.20240.2230sport
14A penalty miss cost the team the match against the league leaderssport0.22130.1561sport
15The coach changed the formation and the team pressed highersport0.31360.1873sport
16The striker signed a new contract after a season of goalssport0.07870.0087sport
17Rain made the pitch heavy but the team kept passing the ballsport0.26170.2549sport
18The captain lifted the cup as fans sang in the stadiumsport0.17400.1449sport
19Training focused on set pieces before the derby matchsport0.30780.2370sport
20The defence held firm and the goalkeeper kept another clean sheetsport0.19250.0558sport
21Chop the onions and garlic then fry them gently in olive oilcooking0.23880.2842cooking
22Add the tomatoes and simmer the sauce for twenty minutescooking0.29320.3200cooking
23Season the soup with salt and pepper before serving it hotcooking0.31720.2824cooking
24Knead the dough until smooth and let it rise in a warm placecooking0.18700.2003cooking
25Roast the vegetables with olive oil garlic and fresh herbscooking0.34060.3854cooking
26Stir the sauce often so the garlic and onions do not burncooking0.30310.3380cooking
27Bake the bread until the crust is golden and sounds hollowcooking0.31170.3283cooking
28Whisk the eggs with sugar then fold in the flour gentlycooking0.19010.2248cooking
29Simmer the beans with tomatoes onions and a pinch of saltcooking0.30260.3520cooking
30Serve the pasta with the tomato sauce and fresh basilcooking0.30150.2702cooking
31Fry the fish in butter and finish it with lemon and herbscooking0.29040.2749cooking
32Let the dough rest before you roll it out and bake itcooking0.23830.2520cooking
33Add stock to the pan and simmer the rice until tendercooking0.29370.1756cooking
34Grate the cheese over the pasta and bake until bubblingcooking0.29150.2778cooking
35Toast the spices in a dry pan before adding the onionscooking0.28150.3419cooking
36Slice the bread and serve it warm with butter and soupcooking0.34230.3104cooking
37Marinate the chicken with garlic lemon and olive oil overnightcooking0.23040.2773cooking
38Taste the sauce and add salt pepper or a little sugarcooking0.25890.2662cooking
39Bake the cake for forty minutes and let it cool on a rackcooking0.25580.2431cooking
40Roast the chicken with garlic herbs and lemon until goldencooking0.31730.3681cooking

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
))
Python

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

LabelTextsShare of textsMean similarity (labeled texts)KnownPrecisionRecallF1
sport200.32790.209620111
cooking200.32790.279320111
finance210.34430.250121111

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

RowTextLabelSimilarityMargin to the next labelKnown label
1The striker scored a late goal and the team won the match at homesport0.17280.1220sport
2Fans cheered as the goalkeeper saved a penalty in the final minutesport0.14810.1145sport
3The coach praised the defence after a clean sheet in the league matchsport0.22320.1360sport
4A thrilling match ended level after the striker hit the post twicesport0.23250.1915sport
5The team trained hard before the cup final against their rivalssport0.32050.2859sport
6Injury kept the captain out of the match but the team still wonsport0.20950.1832sport
7The referee awarded a penalty and the striker scored the winning goalsport0.15830.1199sport
8Supporters filled the stadium to watch the league leaders playsport0.16030.2201sport
9The young winger crossed the ball and the striker headed it homesport0.21430.1541sport
10After the final whistle the coach thanked the fans for their supportsport0.22870.1751sport
11The goalkeeper made three saves to keep the team in the cupsport0.14910.0527sport
12League rivals met in a tense match that ended with a late goalsport0.22350.2158sport
13The team celebrated the title with their fans in the stadiumsport0.20240.2230sport
14A penalty miss cost the team the match against the league leaderssport0.22130.1561sport
15The coach changed the formation and the team pressed highersport0.31360.1873sport
16The striker signed a new contract after a season of goalssport0.07870.0087sport
17Rain made the pitch heavy but the team kept passing the ballsport0.26170.2549sport
18The captain lifted the cup as fans sang in the stadiumsport0.17400.1449sport
19Training focused on set pieces before the derby matchsport0.30780.2370sport
20The defence held firm and the goalkeeper kept another clean sheetsport0.19250.0558sport
21Chop the onions and garlic then fry them gently in olive oilcooking0.23880.2842cooking
22Add the tomatoes and simmer the sauce for twenty minutescooking0.29320.3200cooking
23Season the soup with salt and pepper before serving it hotcooking0.31720.2824cooking
24Knead the dough until smooth and let it rise in a warm placecooking0.18700.2003cooking
25Roast the vegetables with olive oil garlic and fresh herbscooking0.34060.3854cooking
26Stir the sauce often so the garlic and onions do not burncooking0.30310.3380cooking
27Bake the bread until the crust is golden and sounds hollowcooking0.31170.3283cooking
28Whisk the eggs with sugar then fold in the flour gentlycooking0.19010.2248cooking
29Simmer the beans with tomatoes onions and a pinch of saltcooking0.30260.3520cooking
30Serve the pasta with the tomato sauce and fresh basilcooking0.30150.2702cooking
31Fry the fish in butter and finish it with lemon and herbscooking0.29040.2749cooking
32Let the dough rest before you roll it out and bake itcooking0.23830.2520cooking
33Add stock to the pan and simmer the rice until tendercooking0.29370.1756cooking
34Grate the cheese over the pasta and bake until bubblingcooking0.29150.2778cooking
35Toast the spices in a dry pan before adding the onionscooking0.28150.3419cooking
36Slice the bread and serve it warm with butter and soupcooking0.34230.3104cooking
37Marinate the chicken with garlic lemon and olive oil overnightcooking0.23040.2773cooking
38Taste the sauce and add salt pepper or a little sugarcooking0.25890.2662cooking
39Bake the cake for forty minutes and let it cool on a rackcooking0.25580.2431cooking
40Roast the chicken with garlic herbs and lemon until goldencooking0.31730.3681cooking

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,
})
06

Close calls

Reflect

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

Confusion matrixHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?
View data
churnedchurn_probability
no0.1130
no0.1960
no0.0150
no0.4510
no0.0820
no0.0180
yes0.9500
no0.5490
no0.1550
no0.5380
no0.2070
no0.1630
no0.0720
no0.4190
yes0.8590
no0.0530
no0.2970
no0.0430
no0.0910
no0.0760
no0.0610
no0.4490
no0.0870
no0.1210
no0.0970
no0.7310
no0.3160
no0.1260
no0.1460
no0.1380
no0.0600
no0.0700
no0.0640
no0.5060
no0.7570
no0.0910
no0.0910
no0.1450
no0.0850
yes0.9210
yes0.9000
no0.3470
no0.1580
no0.0060
no0.0520
no0.2120
no0.2060
no0.1880
yes0.8940
no0.5160
no0.0660
no0.0320
yes0.8820
no0.1710
no0.6350
no0.1400
no0.1350
no0.0600
no0.4720
no0.1760

First 60 of 1000 rows.

07

Check your understanding

Checkpoint

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

08

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