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)withdimthe 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 | |
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
windowis 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
termsholding the queries. -
**kwargs–Passed on to
search, e.g.lemma_column=orfile_id_column=.
Returns:
-
DataFrame–termswith a "vector" column ofArray(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 | |
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)-- whatencodeproduces. -
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 | |
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 whenshow_labelsis 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 | |