Skip to content

ADescribe · describe.zero_shot_text

Zero-shot text labels (sentence embeddings)

Which of the labels I name does each text fit best, without training a model on labeled examples?

Sorts each text into one of the labels you name by meaning. Each text and each label (written into a short sentence such as "This text is about sport.") becomes an all-MiniLM-L6-v2 sentence embedding, and the text takes the label it is most similar to by cosine. The margin to the second-best label shows how clear each call is. With a column of known labels the method also reports accuracy, macro F1 and a confusion matrix, so you can see whether the labels work before you rely on them. The embedder runs on this computer after a one-time download you approve (about 90 MB); Python and R compute the same numbers.

Verified in Python and R Python and R agree to 6 decimals Also called zero-shot classification, zero-shot text classification, label texts without training…

A real result

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

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

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

Worked examples in the app

  • Corpus themesml_corpus · text: text · truth: theme
  • Corpus truth levels templateml_corpus · text: text · truth: theme
  • Reviews aspectss5_reviews · text: review text
  • Reviews floor bare labelss5_reviews · text: review text
  • Invalid one labelml_corpus · text: text
  • Invalid template no slotml_corpus · text: text
  • Degenerate all naml_corpus · text: text · truth: theme

In the guides

Where it sits in the decision guides

  • Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
  • LLMs for prediction (zero/few-shot, RAG) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Textcategorical · 1 column
The column of texts to label; each row is one text.
Known labels (optional)categorical · 0–1 column · 2–50 levels
Optional — a column with the right label for some texts; the method then reports how often the zero-shot labels match it.

Choices you make

model

Embedderdefault minilm

The sentence-embedding model that compares texts with labels; it runs on this computer after a one-time download you approve.

  • all-MiniLM-L6-v2 (pretrained, ~90 MB)(default) — A small English sentence-transformer that places texts with similar meaning close together; downloaded once, after you agree.
Labelsdefault —

The labels to choose from, separated by commas. Leave empty to use the levels of the known-labels column.

Label sentencedefault This text is about {label}.

How each label is written before it is embedded; {label} is replaced by the label. A short sentence often works better than a bare word.

options

Minimum similaritydefault —

Texts whose best similarity is below this get no label (counted as wrong when known labels are given). Empty labels every text.

Advanced

Softmax temperaturedefault 0.05

Turns similarities into label probabilities: softmax of similarity ÷ temperature. Smaller values give more confident probabilities.

Checks and remedies

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

  • Label wording

    The labels are matched by meaning, so their wording matters; try more descriptive labels or another sentence if results look off.

  • English text

    all-MiniLM-L6-v2 was trained mostly on English text; other languages need another embedder.

  • No training on your labels

    Zero-shot labels use no labeled examples from your data; when you have enough labeled rows, a trained model in ML Studio usually does better.

What it reports

n_docs
Labels given to texts without training on labeled examples: each text takes the named label whose embedding it is most similar to.
n_labels
Labels given to texts without training on labeled examples: each text takes the named label whose embedding it is most similar to.
embedder
Labels given to texts without training on labeled examples: each text takes the named label whose embedding it is most similar to.
labels_text
Labels given to texts without training on labeled examples: each text takes the named label whose embedding it is most similar to.
mean_best
The cosine of the angle between two vectors: 1 for the same direction, 0 for unrelated, −1 for opposite.
mean_margin
A text's similarity to its best label minus its similarity to the second best; small margins are close calls.
n_unassigned
Texts whose best similarity is below the floor get no label; coverage is the share of texts that got one.
coverage
Texts whose best similarity is below the floor get no label; coverage is the share of texts that got one.
n_evaluated
Accuracy, macro F1 and balanced accuracy of the zero-shot labels on texts whose known label is one of the labels.
n_not_in_labels
Accuracy, macro F1 and balanced accuracy of the zero-shot labels on texts whose known label is one of the labels.
accuracy
Accuracy, macro F1 and balanced accuracy of the zero-shot labels on texts whose known label is one of the labels.
macro_f1
Accuracy, macro F1 and balanced accuracy of the zero-shot labels on texts whose known label is one of the labels.
balanced_accuracy
Accuracy, macro F1 and balanced accuracy of the zero-shot labels on texts whose known label is one of the labels.

Per group, level or term: n[<label>], share[<label>], mean_similarity[<label>], f1[<label>]

Python and R

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

Default traps between the two languages

  • Both engines run the same all-MiniLM-L6-v2 twin in float64 (codesplash.text.minilm ↔ codesplashr text_minilm.R) from the same float32 weights; matrix products use each engine's BLAS, so similarities agree to about 1e-12 rather than exactly.
  • Without the downloaded weights the run stops with CS_WEIGHTS_MISSING in both engines; nothing is downloaded automatically.
Python

The exact script CodeSplash ran for example “Corpus themes” · 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,
})
R

The exact script CodeSplash ran for example “Corpus themes” · 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
))

Sources

  • Reimers N, Gurevych I (2019). Sentence-BERT: sentence embeddings using Siamese BERT-networks. EMNLP-IJCNLP 2019, 3982–3992.
  • Wang W, Wei F, Dong L, Bao H, Yang N, Zhou M (2020). MiniLM: deep self-attention distillation for task-agnostic compression of pre-trained transformers. NeurIPS 33.
  • Yin W, Hay J, Roth D (2019). Benchmarking zero-shot text classification: datasets, evaluation and entailment approach. EMNLP-IJCNLP 2019, 3914–3923.
  • Chang M-W, Ratinov L, Roth D, Srikumar V (2008). Importance of semantic representation: dataless classification. AAAI 2008, 830–835.

From the CodeSplash method registry · describe.zero_shot_text v1.0.0.