Skip to content

Embeddings

encode

encode(
    model: SentenceTransformer, in_expr: IntoExpr
) -> pl.Expr

Encode a text column into fixed-width sentence embeddings using SentenceTransformers.

Parameters:

  • model (SentenceTransformer) –

    Model used to encode in_expr's strings into vectors.

  • in_expr (IntoExpr) –

    Column name or expression holding the text to encode.

Returns:

  • Expr –

    Expression producing one L2-normalized embedding vector per input string, as an Array(Float32, dim) with dim the model's embedding dimension.

References
  • Reimers, N. and I. Gurevych. 2019. Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing. https://arxiv.org/abs/1908.10084
Source code in python/polars_corpus/embeddings.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def encode(model: SentenceTransformer, in_expr: IntoExpr) -> pl.Expr:
    """Encode a text column into fixed-width sentence embeddings using SentenceTransformers.

    Parameters
    ----------
    model : SentenceTransformer
        Model used to encode `in_expr`'s strings into vectors.
    in_expr : IntoExpr
        Column name or expression holding the text to encode.

    Returns
    -------
    pl.Expr
        Expression producing one L2-normalized embedding vector per input
        string, as an `Array(Float32, dim)` with `dim` the model's embedding
        dimension.

    References
    ----------
    - Reimers, N. and I. Gurevych. 2019. Sentence-BERT: Sentence Embeddings using
      Siamese BERT-Networks. *Proceedings of the 2019 Conference on Empirical Methods
      in Natural Language Processing.* https://arxiv.org/abs/1908.10084
    """
    expr = as_expr(in_expr)
    dim = model.get_embedding_dimension()
    return expr.map_batches(
        lambda col: model.encode(col.to_list(), normalize_embeddings=True),
        return_dtype=pl.Array(pl.Float32, dim),
        is_elementwise=True,
    )

encode_terms

encode_terms(
    terms: DataFrame | Series | Sequence[str],
    corpus: DataFrame,
    model: SentenceTransformer,
    expr: IntoExprColumn = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    max_matches: int = 10000,
    seed: Optional[int] = None,
    term_column: str = "token",
    **kwargs,
) -> pl.DataFrame

Give each term a single vector, averaged over its uses in a corpus.

Runs each term as a simple query, encodes every match together with the context it appears in, and averages those into one vector, so that terms used in similar contexts get similar vectors.

Parameters:

  • terms (pl.DataFrame, pl.Series or sequence of str) –

    Terms to encode, as simple queries.

  • corpus (DataFrame) –

    Corpus to search for each term.

  • model (SentenceTransformer) –

    Model used to encode the matches.

  • expr (IntoExprColumn, default: "token" ) –

    Column name or expression holding the text to encode, as in SearchResults.encode.

  • window (int, default: 5 ) –

    Number of tokens of context on both sides of each match.

  • chunk_column (str, default: None ) –

    Column name defining chunk boundaries. When given, context extends to the chunk holding the match and window is ignored.

  • max_matches (int, default: 10000 ) –

    Number of matches to encode per term. Terms with more than this are sampled down to it.

  • seed (int, default: None ) –

    Random seed for that sampling. Set to make results repeatable.

  • term_column (str, default: "token" ) –

    Column of terms holding the queries.

  • **kwargs –

    Passed on to search, e.g. lemma_column= or file_id_column=.

Returns:

  • DataFrame –

    terms with a "vector" column of Array(Float32, dim), holding each term's unit-length centroid. Terms with no matches in the corpus get a null vector.

Examples:

>>> import polars_corpus as plc
>>> from sentence_transformers import SentenceTransformer
>>> model = SentenceTransformer("all-MiniLM-L6-v2")
>>> plc.encode_terms(["bank", "shore", "vault"], corpus, model)
>>> top = corpus.corpus.frequencies("token").head(500)
>>> plc.encode_terms(top, corpus, model, chunk_column="sentence_tag")
Source code in python/polars_corpus/embeddings.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def encode_terms(
    terms: pl.DataFrame | pl.Series | Sequence[str],
    corpus: pl.DataFrame,
    model: SentenceTransformer,
    expr: IntoExprColumn = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    max_matches: int = 10_000,
    seed: Optional[int] = None,
    term_column: str = "token",
    **kwargs,
) -> pl.DataFrame:
    """Give each term a single vector, averaged over its uses in a corpus.

    Runs each term as a simple query, encodes every match together with the
    context it appears in, and averages those into one vector, so that terms
    used in similar contexts get similar vectors.

    Parameters
    ----------
    terms : pl.DataFrame, pl.Series or sequence of str
        Terms to encode, as simple queries.
    corpus : pl.DataFrame
        Corpus to search for each term.
    model : SentenceTransformer
        Model used to encode the matches.
    expr : IntoExprColumn, default "token"
        Column name or expression holding the text to encode, as in
        `SearchResults.encode`.
    window : int, default 5
        Number of tokens of context on both sides of each match.
    chunk_column : str, optional
        Column name defining chunk boundaries. When given, context extends to
        the chunk holding the match and `window` is ignored.
    max_matches : int, default 10000
        Number of matches to encode per term. Terms with more than this are
        sampled down to it.
    seed : int, optional
        Random seed for that sampling. Set to make results repeatable.
    term_column : str, default "token"
        Column of `terms` holding the queries.
    **kwargs
        Passed on to `search`, e.g. `lemma_column=` or `file_id_column=`.

    Returns
    -------
    pl.DataFrame
        `terms` with a "vector" column of `Array(Float32, dim)`, holding each
        term's unit-length centroid. Terms with no matches in the corpus get a
        null vector.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> from sentence_transformers import SentenceTransformer
    >>> model = SentenceTransformer("all-MiniLM-L6-v2")
    >>> plc.encode_terms(["bank", "shore", "vault"], corpus, model)
    >>> top = corpus.corpus.frequencies("token").head(500)
    >>> plc.encode_terms(top, corpus, model, chunk_column="sentence_tag")
    """
    if isinstance(terms, pl.DataFrame):
        frame = terms
    elif isinstance(terms, (pl.Series, list, tuple)):
        frame = pl.DataFrame({term_column: terms})
    else:
        raise ValueError(
            "terms must be a DataFrame with a column of queries, or a Series "
            f"or list of them, got {type(terms).__name__}"
        )
    check_columns(frame, [term_column], name="term list", param="term_column")
    corpus = as_eager(corpus)
    if max_matches < 1:
        raise ValueError(f"max_matches must be a positive integer, got {max_matches}")

    def term_vector(term: str) -> Optional[pl.Series]:
        results = search(corpus, term, **kwargs)
        if results is None:
            return None
        if len(results) > max_matches:
            results = results.sample(max_matches, seed=seed)
        encoded = results.encode(model, expr, window=window, chunk_column=chunk_column)
        return encoded.select(centroid("vector")).item()

    dim = model.get_embedding_dimension()
    return frame.with_columns(
        pl.col(term_column)
        .map_elements(term_vector, return_dtype=pl.Array(pl.Float32, dim))
        .alias("vector")
    )

centroid

centroid(
    in_expr: IntoExpr, normalize: bool = True
) -> pl.Expr

Average a column of embedding vectors into a single vector.

Parameters:

  • in_expr (IntoExpr) –

    Column name or expression holding the vectors, as an Array(Float32, dim) -- what encode produces.

  • normalize (bool, default: True ) –

    Scale the result to unit length. An all-zero centroid is left as it is.

Returns:

  • Expr –

    Aggregating expression producing one vector named "centroid".

Source code in python/polars_corpus/embeddings.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def centroid(in_expr: IntoExpr, normalize: bool = True) -> pl.Expr:
    """Average a column of embedding vectors into a single vector.

    Parameters
    ----------
    in_expr : IntoExpr
        Column name or expression holding the vectors, as an
        `Array(Float32, dim)` -- what `encode` produces.
    normalize : bool, default True
        Scale the result to unit length. An all-zero centroid is
        left as it is.

    Returns
    -------
    pl.Expr
        Aggregating expression producing one vector named "centroid".
    """
    expr = as_expr(in_expr)
    # Arrays don't mean() elementwise, but a struct's fields each mean() on
    # their own, so widen to one column per dimension and gather them back up.
    c = pl.concat_arr(expr.arr.to_struct().struct.unnest().mean()).alias("centroid")
    if normalize:
        x = pl.element()
        norm = (x * x).sum().sqrt()
        denom = pl.when(norm != 0).then(norm).otherwise(1.0)
        c = c.arr.eval(x / denom)
    return c

text_plot

text_plot(
    xy,
    labels,
    ax: Axes | None = None,
    adjust: bool = True,
    show_labels: bool = True,
) -> Axes

Plot labeled points on a two-dimensional map.

Draws each row of xy with its label, for reading a projection of embedding vectors (e.g. from UMAP) down to two dimensions.

Parameters:

  • xy (array-like of shape (n, 2)) –

    Coordinates to plot, one row per label.

  • labels (sequence of str) –

    Label for each row of xy, e.g. the token or the concordance line the vector was built from.

  • ax (Axes, default: None ) –

    Axes to draw on. A new figure and axes are created if not given.

  • adjust (bool, default: True ) –

    Nudge overlapping labels apart with adjustText. Ignored when show_labels is False.

  • show_labels (bool, default: True ) –

    Draw the labels. When False, the points are drawn as a plain scatter instead.

Returns:

  • Axes –

    The axes drawn on.

Examples:

>>> import umap
>>> xy = umap.UMAP().fit_transform(df["vector"].to_numpy())
>>> plc.text_plot(xy, df["token"])
>>> plc.text_plot(xy, df["token"], show_labels=False)
Source code in python/polars_corpus/visualizations.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
def text_plot(
    xy, labels, ax: Axes | None = None, adjust: bool = True, show_labels: bool = True
) -> Axes:
    """
    Plot labeled points on a two-dimensional map.

    Draws each row of `xy` with its label, for reading a projection of
    embedding vectors (e.g. from UMAP) down to two dimensions.

    Parameters
    ----------
    xy : array-like of shape (n, 2)
        Coordinates to plot, one row per label.
    labels : sequence of str
        Label for each row of `xy`, e.g. the token or the concordance line the
        vector was built from.
    ax : Axes, optional
        Axes to draw on. A new figure and axes are created if not given.
    adjust : bool, default True
        Nudge overlapping labels apart with `adjustText`. Ignored when
        `show_labels` is False.
    show_labels : bool, default True
        Draw the labels. When False, the points are drawn as a plain scatter
        instead.

    Returns
    -------
    Axes
        The axes drawn on.

    Examples
    --------
    >>> import umap
    >>> xy = umap.UMAP().fit_transform(df["vector"].to_numpy())
    >>> plc.text_plot(xy, df["token"])
    >>> plc.text_plot(xy, df["token"], show_labels=False)
    """
    if ax is None:
        _, ax = plt.subplots()

    # Labeled points are placed by their text, so the marker only shows where
    # there is nothing else to see.
    size = 0 if show_labels else 5
    ax.scatter(xy[:, 0], xy[:, 1], s=size)

    if show_labels:
        texts = []
        for point, label in zip(xy, labels):
            texts.append(ax.text(point[0], point[1], label, ha="center", va="center"))

        if adjust:
            try:
                from adjustText import adjust_text
            except ImportError:
                raise ImportError(
                    "text_plot(adjust=True) needs adjustText: "
                    "pip install 'polars-corpus[embeddings]', or pass adjust=False"
                ) from None
            adjust_text(texts, ax=ax, time_lim=2)

    for spine in ax.spines.values():
        spine.set_visible(False)

    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_aspect(1)

    return ax