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.
A real result
Example “Corpus themes”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
61 texts into 3 labels; most common finance (34%); accuracy 100% against theme.
- Texts
- 61
- Labels
- 3
- Mean margin
- 0.2229
- Accuracy
- 100.0%
- Macro F1
- 1
Plots
View data
| Texts | Label |
|---|---|
| 20 | sport |
| 20 | cooking |
| 21 | finance |
View data
| Margin |
|---|
| 0.1220 |
| 0.1145 |
| 0.1360 |
| 0.1915 |
| 0.2859 |
| 0.1832 |
| 0.1199 |
| 0.2201 |
| 0.1541 |
| 0.1751 |
| 0.0527 |
| 0.2158 |
| 0.2230 |
| 0.1561 |
| 0.1873 |
| 0.0087 |
| 0.2549 |
| 0.1449 |
| 0.2370 |
| 0.0558 |
| 0.2842 |
| 0.3200 |
| 0.2824 |
| 0.2003 |
| 0.3854 |
| 0.3380 |
| 0.3283 |
| 0.2248 |
| 0.3520 |
| 0.2702 |
| 0.2749 |
| 0.2520 |
| 0.1756 |
| 0.2778 |
| 0.3419 |
| 0.3104 |
| 0.2773 |
| 0.2662 |
| 0.2431 |
| 0.3681 |
| 0.2081 |
| 0.2676 |
| 0.1135 |
| 0.2104 |
| 0.2483 |
| 0.2883 |
| 0.1367 |
| 0.1742 |
| 0.3109 |
| 0.2776 |
| 0.2029 |
| 0.2837 |
| 0.1654 |
| 0.2936 |
| 0.1464 |
| 0.2009 |
| 0.2805 |
| 0.2096 |
| 0.2340 |
| 0.2634 |
First 60 of 61 rows.
View data
| theme | Zero-shot label |
|---|---|
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| sport | sport |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| cooking | cooking |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
| finance | finance |
First 60 of 61 rows.
Assumptions
- Label wording — Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result.
- English text — all-MiniLM-L6-v2 was trained mostly on English text.
- No training on your labels — No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better.
Labels
| Label | Texts | Share of texts | Mean similarity (labeled texts) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| sport | 20 | 0.3279 | 0.2096 | 20 | 1 | 1 | 1 |
| cooking | 20 | 0.3279 | 0.2793 | 20 | 1 | 1 | 1 |
| finance | 21 | 0.3443 | 0.2501 | 21 | 1 | 1 | 1 |
Each label is embedded as “This text is about {label}.” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings.
Labeled texts
| Row | Text | Label | Similarity | Margin to the next label | Known label |
|---|---|---|---|---|---|
| 1 | The striker scored a late goal and the team won the match at home | sport | 0.1728 | 0.1220 | sport |
| 2 | Fans cheered as the goalkeeper saved a penalty in the final minute | sport | 0.1481 | 0.1145 | sport |
| 3 | The coach praised the defence after a clean sheet in the league match | sport | 0.2232 | 0.1360 | sport |
| 4 | A thrilling match ended level after the striker hit the post twice | sport | 0.2325 | 0.1915 | sport |
| 5 | The team trained hard before the cup final against their rivals | sport | 0.3205 | 0.2859 | sport |
| 6 | Injury kept the captain out of the match but the team still won | sport | 0.2095 | 0.1832 | sport |
| 7 | The referee awarded a penalty and the striker scored the winning goal | sport | 0.1583 | 0.1199 | sport |
| 8 | Supporters filled the stadium to watch the league leaders play | sport | 0.1603 | 0.2201 | sport |
| 9 | The young winger crossed the ball and the striker headed it home | sport | 0.2143 | 0.1541 | sport |
| 10 | After the final whistle the coach thanked the fans for their support | sport | 0.2287 | 0.1751 | sport |
| 11 | The goalkeeper made three saves to keep the team in the cup | sport | 0.1491 | 0.0527 | sport |
| 12 | League rivals met in a tense match that ended with a late goal | sport | 0.2235 | 0.2158 | sport |
| 13 | The team celebrated the title with their fans in the stadium | sport | 0.2024 | 0.2230 | sport |
| 14 | A penalty miss cost the team the match against the league leaders | sport | 0.2213 | 0.1561 | sport |
| 15 | The coach changed the formation and the team pressed higher | sport | 0.3136 | 0.1873 | sport |
| 16 | The striker signed a new contract after a season of goals | sport | 0.0787 | 0.0087 | sport |
| 17 | Rain made the pitch heavy but the team kept passing the ball | sport | 0.2617 | 0.2549 | sport |
| 18 | The captain lifted the cup as fans sang in the stadium | sport | 0.1740 | 0.1449 | sport |
| 19 | Training focused on set pieces before the derby match | sport | 0.3078 | 0.2370 | sport |
| 20 | The defence held firm and the goalkeeper kept another clean sheet | sport | 0.1925 | 0.0558 | sport |
| 21 | Chop the onions and garlic then fry them gently in olive oil | cooking | 0.2388 | 0.2842 | cooking |
| 22 | Add the tomatoes and simmer the sauce for twenty minutes | cooking | 0.2932 | 0.3200 | cooking |
| 23 | Season the soup with salt and pepper before serving it hot | cooking | 0.3172 | 0.2824 | cooking |
| 24 | Knead the dough until smooth and let it rise in a warm place | cooking | 0.1870 | 0.2003 | cooking |
| 25 | Roast the vegetables with olive oil garlic and fresh herbs | cooking | 0.3406 | 0.3854 | cooking |
| 26 | Stir the sauce often so the garlic and onions do not burn | cooking | 0.3031 | 0.3380 | cooking |
| 27 | Bake the bread until the crust is golden and sounds hollow | cooking | 0.3117 | 0.3283 | cooking |
| 28 | Whisk the eggs with sugar then fold in the flour gently | cooking | 0.1901 | 0.2248 | cooking |
| 29 | Simmer the beans with tomatoes onions and a pinch of salt | cooking | 0.3026 | 0.3520 | cooking |
| 30 | Serve the pasta with the tomato sauce and fresh basil | cooking | 0.3015 | 0.2702 | cooking |
| 31 | Fry the fish in butter and finish it with lemon and herbs | cooking | 0.2904 | 0.2749 | cooking |
| 32 | Let the dough rest before you roll it out and bake it | cooking | 0.2383 | 0.2520 | cooking |
| 33 | Add stock to the pan and simmer the rice until tender | cooking | 0.2937 | 0.1756 | cooking |
| 34 | Grate the cheese over the pasta and bake until bubbling | cooking | 0.2915 | 0.2778 | cooking |
| 35 | Toast the spices in a dry pan before adding the onions | cooking | 0.2815 | 0.3419 | cooking |
| 36 | Slice the bread and serve it warm with butter and soup | cooking | 0.3423 | 0.3104 | cooking |
| 37 | Marinate the chicken with garlic lemon and olive oil overnight | cooking | 0.2304 | 0.2773 | cooking |
| 38 | Taste the sauce and add salt pepper or a little sugar | cooking | 0.2589 | 0.2662 | cooking |
| 39 | Bake the cake for forty minutes and let it cool on a rack | cooking | 0.2558 | 0.2431 | cooking |
| 40 | Roast the chicken with garlic herbs and lemon until golden | cooking | 0.3173 | 0.3681 | cooking |
First 40 of 61 rows.
- 1 of 62 rows were left out because a value was missing.
- Labels are probabilities from a softmax of similarity ÷ 0.05; the predicted label is the most similar one (ties go to the label listed first).
61 texts into 3 labels; most common finance (34%); accuracy 100% against theme.
- Texts
- 61
- Labels
- 3
- Mean margin
- 0.2229
- Accuracy
- 100.0%
- Macro F1
- 1
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Label wording — Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result.
- English text — all-MiniLM-L6-v2 was trained mostly on English text.
- No training on your labels — No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better.
Labels
| Label | Texts | Share of texts | Mean similarity (labeled texts) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| sport | 20 | 0.3279 | 0.2096 | 20 | 1 | 1 | 1 |
| cooking | 20 | 0.3279 | 0.2793 | 20 | 1 | 1 | 1 |
| finance | 21 | 0.3443 | 0.2501 | 21 | 1 | 1 | 1 |
Each label is embedded as “This text is about {label}.” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings.
Labeled texts
| Row | Text | Label | Similarity | Margin to the next label | Known label |
|---|---|---|---|---|---|
| 1 | The striker scored a late goal and the team won the match at home | sport | 0.1728 | 0.1220 | sport |
| 2 | Fans cheered as the goalkeeper saved a penalty in the final minute | sport | 0.1481 | 0.1145 | sport |
| 3 | The coach praised the defence after a clean sheet in the league match | sport | 0.2232 | 0.1360 | sport |
| 4 | A thrilling match ended level after the striker hit the post twice | sport | 0.2325 | 0.1915 | sport |
| 5 | The team trained hard before the cup final against their rivals | sport | 0.3205 | 0.2859 | sport |
| 6 | Injury kept the captain out of the match but the team still won | sport | 0.2095 | 0.1832 | sport |
| 7 | The referee awarded a penalty and the striker scored the winning goal | sport | 0.1583 | 0.1199 | sport |
| 8 | Supporters filled the stadium to watch the league leaders play | sport | 0.1603 | 0.2201 | sport |
| 9 | The young winger crossed the ball and the striker headed it home | sport | 0.2143 | 0.1541 | sport |
| 10 | After the final whistle the coach thanked the fans for their support | sport | 0.2287 | 0.1751 | sport |
| 11 | The goalkeeper made three saves to keep the team in the cup | sport | 0.1491 | 0.0527 | sport |
| 12 | League rivals met in a tense match that ended with a late goal | sport | 0.2235 | 0.2158 | sport |
| 13 | The team celebrated the title with their fans in the stadium | sport | 0.2024 | 0.2230 | sport |
| 14 | A penalty miss cost the team the match against the league leaders | sport | 0.2213 | 0.1561 | sport |
| 15 | The coach changed the formation and the team pressed higher | sport | 0.3136 | 0.1873 | sport |
| 16 | The striker signed a new contract after a season of goals | sport | 0.0787 | 0.0087 | sport |
| 17 | Rain made the pitch heavy but the team kept passing the ball | sport | 0.2617 | 0.2549 | sport |
| 18 | The captain lifted the cup as fans sang in the stadium | sport | 0.1740 | 0.1449 | sport |
| 19 | Training focused on set pieces before the derby match | sport | 0.3078 | 0.2370 | sport |
| 20 | The defence held firm and the goalkeeper kept another clean sheet | sport | 0.1925 | 0.0558 | sport |
| 21 | Chop the onions and garlic then fry them gently in olive oil | cooking | 0.2388 | 0.2842 | cooking |
| 22 | Add the tomatoes and simmer the sauce for twenty minutes | cooking | 0.2932 | 0.3200 | cooking |
| 23 | Season the soup with salt and pepper before serving it hot | cooking | 0.3172 | 0.2824 | cooking |
| 24 | Knead the dough until smooth and let it rise in a warm place | cooking | 0.1870 | 0.2003 | cooking |
| 25 | Roast the vegetables with olive oil garlic and fresh herbs | cooking | 0.3406 | 0.3854 | cooking |
| 26 | Stir the sauce often so the garlic and onions do not burn | cooking | 0.3031 | 0.3380 | cooking |
| 27 | Bake the bread until the crust is golden and sounds hollow | cooking | 0.3117 | 0.3283 | cooking |
| 28 | Whisk the eggs with sugar then fold in the flour gently | cooking | 0.1901 | 0.2248 | cooking |
| 29 | Simmer the beans with tomatoes onions and a pinch of salt | cooking | 0.3026 | 0.3520 | cooking |
| 30 | Serve the pasta with the tomato sauce and fresh basil | cooking | 0.3015 | 0.2702 | cooking |
| 31 | Fry the fish in butter and finish it with lemon and herbs | cooking | 0.2904 | 0.2749 | cooking |
| 32 | Let the dough rest before you roll it out and bake it | cooking | 0.2383 | 0.2520 | cooking |
| 33 | Add stock to the pan and simmer the rice until tender | cooking | 0.2937 | 0.1756 | cooking |
| 34 | Grate the cheese over the pasta and bake until bubbling | cooking | 0.2915 | 0.2778 | cooking |
| 35 | Toast the spices in a dry pan before adding the onions | cooking | 0.2815 | 0.3419 | cooking |
| 36 | Slice the bread and serve it warm with butter and soup | cooking | 0.3423 | 0.3104 | cooking |
| 37 | Marinate the chicken with garlic lemon and olive oil overnight | cooking | 0.2304 | 0.2773 | cooking |
| 38 | Taste the sauce and add salt pepper or a little sugar | cooking | 0.2589 | 0.2662 | cooking |
| 39 | Bake the cake for forty minutes and let it cool on a rack | cooking | 0.2558 | 0.2431 | cooking |
| 40 | Roast the chicken with garlic herbs and lemon until golden | cooking | 0.3173 | 0.3681 | cooking |
First 40 of 61 rows.
- 1 of 62 rows were left out because a value was missing.
- Labels are probabilities from a softmax of similarity ÷ 0.05; the predicted label is the most similar one (ties go to the label listed first).
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.
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,
})
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.