model2vec 0.3.7__tar.gz → 0.3.8__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {model2vec-0.3.7 → model2vec-0.3.8}/PKG-INFO +1 -1
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/distill/distillation.py +17 -7
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/distill/inference.py +11 -9
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/hf_utils.py +0 -1
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/model.py +18 -8
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/version.py +1 -1
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec.egg-info/PKG-INFO +1 -1
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec.egg-info/SOURCES.txt +1 -2
- {model2vec-0.3.7 → model2vec-0.3.8}/tests/test_distillation.py +1 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tutorials/README.md +0 -1
- model2vec-0.3.7/tutorials/semantic_deduplication.ipynb +0 -552
- {model2vec-0.3.7 → model2vec-0.3.8}/.github/workflows/ci.yaml +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/.gitignore +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/.pre-commit-config.yaml +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/LICENSE +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/Makefile +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/README.md +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/logo.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/logo_v2.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/model2vec_model_diagram.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/model2vec_model_diagram_transparant_dark.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/model2vec_model_diagram_transparant_light.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/sentences_per_second_vs_average_score.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/speed_vs_accuracy.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/speed_vs_accuracy_v2.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/speed_vs_accuracy_v3.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/speed_vs_accuracy_v4.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/speed_vs_mteb_score.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/speed_vs_mteb_score_v2.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/assets/images/tutorial_ezlo.png +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/__init__.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/distill/__init__.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/distill/tokenizer.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/distill/utils.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/model_card_template.md +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec/utils.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec.egg-info/dependency_links.txt +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec.egg-info/requires.txt +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/model2vec.egg-info/top_level.txt +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/pyproject.toml +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/results/README.md +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/scripts/export_to_onnx.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/setup.cfg +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tests/__init__.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tests/conftest.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tests/data/test_tokenizer/special_tokens_map.json +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tests/data/test_tokenizer/tokenizer.json +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tests/data/test_tokenizer/tokenizer_config.json +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tests/test_model.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tests/test_utils.py +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tutorials/recipe_search.ipynb +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/tutorials/semantic_chunking.ipynb +0 -0
- {model2vec-0.3.7 → model2vec-0.3.8}/uv.lock +0 -0
|
@@ -13,8 +13,8 @@ from tokenizers.models import BPE, Unigram
|
|
|
13
13
|
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
|
|
14
14
|
|
|
15
15
|
from model2vec.distill.inference import (
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
create_output_embeddings_from_model,
|
|
17
|
+
create_output_embeddings_from_model_and_tokens,
|
|
18
18
|
)
|
|
19
19
|
from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
|
|
20
20
|
from model2vec.distill.utils import select_optimal_device
|
|
@@ -31,7 +31,7 @@ except ImportError:
|
|
|
31
31
|
logger = logging.getLogger(__name__)
|
|
32
32
|
|
|
33
33
|
|
|
34
|
-
PCADimType = Union[int, None, Literal["auto"]]
|
|
34
|
+
PCADimType = Union[int, None, float, Literal["auto"]]
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
def distill_from_model(
|
|
@@ -88,7 +88,7 @@ def distill_from_model(
|
|
|
88
88
|
tokens: list[str] = []
|
|
89
89
|
if use_subword:
|
|
90
90
|
# Create the subword embeddings.
|
|
91
|
-
tokens, embeddings =
|
|
91
|
+
tokens, embeddings = create_output_embeddings_from_model(model=model, tokenizer=tokenizer, device=device)
|
|
92
92
|
new_tokenizer, embeddings = _remove_tokens_and_embeddings(tokenizer, token_remove_pattern, tokens, embeddings)
|
|
93
93
|
else:
|
|
94
94
|
# We need to keep the unk token in the tokenizer.
|
|
@@ -111,7 +111,7 @@ def distill_from_model(
|
|
|
111
111
|
# Only create embeddings if we have tokens to add.
|
|
112
112
|
if cleaned_vocabulary:
|
|
113
113
|
# Create the embeddings.
|
|
114
|
-
_, token_embeddings =
|
|
114
|
+
_, token_embeddings = create_output_embeddings_from_model_and_tokens(
|
|
115
115
|
model=model,
|
|
116
116
|
tokenizer=tokenizer,
|
|
117
117
|
tokens=cleaned_vocabulary,
|
|
@@ -185,6 +185,10 @@ def _remove_tokens_and_embeddings(
|
|
|
185
185
|
|
|
186
186
|
# Remove the unused tokens from the tokenizer.
|
|
187
187
|
new_tokenizer = remove_tokens(tokenizer.backend_tokenizer, wrong_tokens)
|
|
188
|
+
if new_tokenizer.get_vocab_size() == tokenizer.backend_tokenizer.get_vocab_size():
|
|
189
|
+
# This happens if we didn't remove any tokens.
|
|
190
|
+
return new_tokenizer, embeddings
|
|
191
|
+
|
|
188
192
|
# Remove the embeddings of the unused tokens.
|
|
189
193
|
embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
|
|
190
194
|
logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
|
|
@@ -199,6 +203,7 @@ def distill(
|
|
|
199
203
|
pca_dims: PCADimType = 256,
|
|
200
204
|
apply_zipf: bool = True,
|
|
201
205
|
use_subword: bool = True,
|
|
206
|
+
token_remove_pattern: str | None = r"\[unused\d+\]",
|
|
202
207
|
) -> StaticModel:
|
|
203
208
|
"""
|
|
204
209
|
Distill a staticmodel from a sentence transformer.
|
|
@@ -217,6 +222,7 @@ def distill(
|
|
|
217
222
|
If this is 'auto', we don't reduce dimenionality, but still apply PCA.
|
|
218
223
|
:param apply_zipf: Whether to apply Zipf weighting to the embeddings.
|
|
219
224
|
:param use_subword: Whether to keep subword tokens in the vocabulary. If this is False, you must pass a vocabulary, and the returned tokenizer will only detect full words.
|
|
225
|
+
:param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to this regex pattern will be removed from the vocabulary.
|
|
220
226
|
:return: A StaticModel
|
|
221
227
|
|
|
222
228
|
"""
|
|
@@ -231,6 +237,7 @@ def distill(
|
|
|
231
237
|
pca_dims=pca_dims,
|
|
232
238
|
apply_zipf=apply_zipf,
|
|
233
239
|
use_subword=use_subword,
|
|
240
|
+
token_remove_pattern=token_remove_pattern,
|
|
234
241
|
)
|
|
235
242
|
|
|
236
243
|
|
|
@@ -251,10 +258,13 @@ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: PCADimType, apply
|
|
|
251
258
|
f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
|
|
252
259
|
)
|
|
253
260
|
elif pca_dims <= embeddings.shape[1]:
|
|
254
|
-
|
|
261
|
+
if isinstance(pca_dims, float):
|
|
262
|
+
logger.info(f"Applying PCA with {pca_dims} explained variance.")
|
|
263
|
+
else:
|
|
264
|
+
logger.info(f"Applying PCA with n_components {pca_dims}")
|
|
255
265
|
|
|
256
266
|
orig_dims = embeddings.shape[1]
|
|
257
|
-
p = PCA(n_components=pca_dims,
|
|
267
|
+
p = PCA(n_components=pca_dims, svd_solver="full")
|
|
258
268
|
embeddings = p.fit_transform(embeddings)
|
|
259
269
|
|
|
260
270
|
if embeddings.shape[1] < orig_dims:
|
|
@@ -24,18 +24,19 @@ class ModulewithWeights(Protocol):
|
|
|
24
24
|
weight: torch.nn.Parameter
|
|
25
25
|
|
|
26
26
|
|
|
27
|
-
def
|
|
27
|
+
def create_output_embeddings_from_model_and_tokens(
|
|
28
28
|
model: PreTrainedModel,
|
|
29
29
|
tokenizer: PreTrainedTokenizer,
|
|
30
30
|
tokens: list[str],
|
|
31
31
|
device: str,
|
|
32
32
|
) -> tuple[list[str], np.ndarray]:
|
|
33
33
|
"""
|
|
34
|
-
Create output embeddings for a bunch of tokens
|
|
34
|
+
Create output embeddings for a bunch of tokens using a pretrained model.
|
|
35
35
|
|
|
36
|
-
It does a forward pass for all tokens passed in tokens
|
|
36
|
+
It does a forward pass for all tokens passed in `tokens`.
|
|
37
37
|
|
|
38
|
-
:param model: The model
|
|
38
|
+
:param model: The model to use.
|
|
39
|
+
This should be a transformers model.
|
|
39
40
|
:param tokenizer: The tokenizer to use.
|
|
40
41
|
:param tokens: The tokens to use.
|
|
41
42
|
:param device: The torch device to use.
|
|
@@ -99,17 +100,18 @@ def _encode_mean_using_model(model: PreTrainedModel, tokenizer: PreTrainedTokeni
|
|
|
99
100
|
return result / divisor[:, None]
|
|
100
101
|
|
|
101
102
|
|
|
102
|
-
def
|
|
103
|
+
def create_output_embeddings_from_model(
|
|
103
104
|
model: PreTrainedModel,
|
|
104
105
|
tokenizer: PreTrainedTokenizer,
|
|
105
106
|
device: str,
|
|
106
107
|
) -> tuple[list[str], np.ndarray]:
|
|
107
108
|
"""
|
|
108
|
-
Create output embeddings for a bunch of tokens
|
|
109
|
+
Create output embeddings for a bunch of tokens using a pretrained model.
|
|
109
110
|
|
|
110
|
-
It does a forward pass for all
|
|
111
|
+
It does a forward pass for all tokens passed in the tokenizer vocabulary.
|
|
111
112
|
|
|
112
|
-
:param model: The model
|
|
113
|
+
:param model: The model to use.
|
|
114
|
+
This should be a transformers model.
|
|
113
115
|
:param tokenizer: The tokenizer to use.
|
|
114
116
|
:param device: The torch device to use.
|
|
115
117
|
:return: The tokens and output embeddings.
|
|
@@ -157,7 +159,7 @@ def create_output_embeddings_from_model_name(
|
|
|
157
159
|
out = out.float()
|
|
158
160
|
|
|
159
161
|
# Add the output to the intermediate weights
|
|
160
|
-
intermediate_weights.append(out
|
|
162
|
+
intermediate_weights.append(out.mean(1).detach().cpu().numpy())
|
|
161
163
|
|
|
162
164
|
# Concatenate the intermediate weights
|
|
163
165
|
out_weights = np.concatenate(intermediate_weights)
|
|
@@ -35,7 +35,7 @@ class StaticModel:
|
|
|
35
35
|
:param vectors: The vectors to use.
|
|
36
36
|
:param tokenizer: The Transformers tokenizer to use.
|
|
37
37
|
:param config: Any metadata config.
|
|
38
|
-
:param normalize: Whether to normalize.
|
|
38
|
+
:param normalize: Whether to normalize the embeddings.
|
|
39
39
|
:param base_model_name: The used base model name. Used for creating a model card.
|
|
40
40
|
:param language: The language of the model. Used for creating a model card.
|
|
41
41
|
:raises: ValueError if the number of tokens does not match the number of vectors.
|
|
@@ -114,13 +114,14 @@ class StaticModel:
|
|
|
114
114
|
model_name=model_name,
|
|
115
115
|
)
|
|
116
116
|
|
|
117
|
-
def tokenize(self, sentences: list[str], max_length: int | None = None) -> list[int]:
|
|
117
|
+
def tokenize(self, sentences: list[str], max_length: int | None = None) -> list[list[int]]:
|
|
118
118
|
"""
|
|
119
|
-
Tokenize a
|
|
119
|
+
Tokenize a list of sentences.
|
|
120
120
|
|
|
121
|
-
:param sentences: The
|
|
122
|
-
:param max_length: The maximum length of the
|
|
123
|
-
|
|
121
|
+
:param sentences: The sentences to tokenize.
|
|
122
|
+
:param max_length: The maximum length of the sentences in tokens. If this is None, sequences
|
|
123
|
+
are not truncated.
|
|
124
|
+
:return: A list of list of tokens.
|
|
124
125
|
"""
|
|
125
126
|
if max_length is not None:
|
|
126
127
|
m = max_length * self.median_token_length
|
|
@@ -148,6 +149,7 @@ class StaticModel:
|
|
|
148
149
|
cls: type[StaticModel],
|
|
149
150
|
path: PathLike,
|
|
150
151
|
token: str | None = None,
|
|
152
|
+
normalize: bool | None = None,
|
|
151
153
|
) -> StaticModel:
|
|
152
154
|
"""
|
|
153
155
|
Load a StaticModel from a local path or huggingface hub path.
|
|
@@ -156,6 +158,7 @@ class StaticModel:
|
|
|
156
158
|
|
|
157
159
|
:param path: The path to load your static model from.
|
|
158
160
|
:param token: The huggingface token to use.
|
|
161
|
+
:param normalize: Whether to normalize the embeddings.
|
|
159
162
|
:return: A StaticModel
|
|
160
163
|
"""
|
|
161
164
|
from model2vec.hf_utils import load_pretrained
|
|
@@ -163,7 +166,12 @@ class StaticModel:
|
|
|
163
166
|
embeddings, tokenizer, config, metadata = load_pretrained(path, token=token, from_sentence_transformers=False)
|
|
164
167
|
|
|
165
168
|
return cls(
|
|
166
|
-
embeddings,
|
|
169
|
+
embeddings,
|
|
170
|
+
tokenizer,
|
|
171
|
+
config,
|
|
172
|
+
normalize=normalize,
|
|
173
|
+
base_model_name=metadata.get("base_model"),
|
|
174
|
+
language=metadata.get("language"),
|
|
167
175
|
)
|
|
168
176
|
|
|
169
177
|
@classmethod
|
|
@@ -171,6 +179,7 @@ class StaticModel:
|
|
|
171
179
|
cls: type[StaticModel],
|
|
172
180
|
path: PathLike,
|
|
173
181
|
token: str | None = None,
|
|
182
|
+
normalize: bool | None = None,
|
|
174
183
|
) -> StaticModel:
|
|
175
184
|
"""
|
|
176
185
|
Load a StaticModel trained with sentence transformers from a local path or huggingface hub path.
|
|
@@ -179,13 +188,14 @@ class StaticModel:
|
|
|
179
188
|
|
|
180
189
|
:param path: The path to load your static model from.
|
|
181
190
|
:param token: The huggingface token to use.
|
|
191
|
+
:param normalize: Whether to normalize the embeddings.
|
|
182
192
|
:return: A StaticModel
|
|
183
193
|
"""
|
|
184
194
|
from model2vec.hf_utils import load_pretrained
|
|
185
195
|
|
|
186
196
|
embeddings, tokenizer, config, _ = load_pretrained(path, token=token, from_sentence_transformers=True)
|
|
187
197
|
|
|
188
|
-
return cls(embeddings, tokenizer, config, base_model_name=None, language=None)
|
|
198
|
+
return cls(embeddings, tokenizer, config, normalize=normalize, base_model_name=None, language=None)
|
|
189
199
|
|
|
190
200
|
def encode_as_sequence(
|
|
191
201
|
self,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
__version_triple__ = (0, 3,
|
|
1
|
+
__version_triple__ = (0, 3, 8)
|
|
2
2
|
__version__ = ".".join(map(str, __version_triple__))
|
|
@@ -37,6 +37,7 @@ rng = np.random.default_rng()
|
|
|
37
37
|
(None, True, "auto", False), # Subword, PCA set to 'auto'
|
|
38
38
|
(None, True, 1024, False), # Subword, PCA set to high number.
|
|
39
39
|
(None, True, None, True), # No PCA applied
|
|
40
|
+
(None, True, 0.9, True), # PCA as float applied
|
|
40
41
|
(["wordA", "wordB"], False, 4, True), # Custom vocab without subwords PCA and Zipf applied
|
|
41
42
|
(None, False, 256, True), # use_subword = False without passing a vocabulary should raise an error
|
|
42
43
|
],
|
|
@@ -12,5 +12,4 @@ This is a list of all our tutorials. They are all self-contained ipython noteboo
|
|
|
12
12
|
| | what? | Link |
|
|
13
13
|
|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------|
|
|
14
14
|
| **Recipe search** 🍝 | Learn how to do lightning-fast semantic search by distilling a small model. Compare a really tiny model to a larger with one with a better vocabulary. Learn what Fattoush is (delicious). | [](https://colab.research.google.com/github/minishlab/model2vec/blob/master/tutorials/recipe_search.ipynb) |
|
|
15
|
-
| **Semantic deduplication** 🧹 | Learn how Model2Vec can be used to detect duplicate texts. Clean your dataset efficiently by finding both exact and semantic duplicates. Detect train-test leakage. | [](https://colab.research.google.com/github/minishlab/model2vec/blob/master/tutorials/semantic_deduplication.ipynb) |
|
|
16
15
|
| **Semantic chunking** 🧩 | Learn how to chunk your text into meaningful segments with [Chonkie](https://github.com/bhavnicksm/chonkie) at lightning-speed. Efficiently query your chunks with [Vicinity](https://github.com/MinishLab/vicinity). | [](https://colab.research.google.com/github/minishlab/model2vec/blob/master/tutorials/semantic_chunking.ipynb) |
|
|
@@ -1,552 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"cells": [
|
|
3
|
-
{
|
|
4
|
-
"cell_type": "markdown",
|
|
5
|
-
"metadata": {},
|
|
6
|
-
"source": [
|
|
7
|
-
"**Semantic Deduplication with Model2Vec**\n",
|
|
8
|
-
"\n",
|
|
9
|
-
"In this tutorial, we’ll explore how Model2Vec can help identify duplicates in text data that traditional exact matching would miss. While exact matching works for identical texts, it fails to detect near-duplicates—documents that may differ slightly in wording but convey the same meaning. Using Model2Vec, we embed documents into vectors and measure their similarity. This allows us to catch both exact and semantic duplicates, improving the quality of our dataset. With Model2Vec’s speed and efficiency, we can very efficiently perform deduplication on large datasets, ensuring cleaner, more robust data for downstream tasks. Additionally, we will use Model2Vec to detect train-test overlap, ensuring our models are not overfitting."
|
|
10
|
-
]
|
|
11
|
-
},
|
|
12
|
-
{
|
|
13
|
-
"cell_type": "code",
|
|
14
|
-
"execution_count": null,
|
|
15
|
-
"metadata": {},
|
|
16
|
-
"outputs": [],
|
|
17
|
-
"source": [
|
|
18
|
-
"!pip install datasets model2vec reach numpy wordllama tqdm datasketch\n",
|
|
19
|
-
"\n",
|
|
20
|
-
"from difflib import ndiff\n",
|
|
21
|
-
"from time import perf_counter\n",
|
|
22
|
-
"\n",
|
|
23
|
-
"from datasets import load_dataset\n",
|
|
24
|
-
"from datasketch import MinHash, MinHashLSH\n",
|
|
25
|
-
"import numpy as np\n",
|
|
26
|
-
"from model2vec import StaticModel\n",
|
|
27
|
-
"from reach import Reach\n",
|
|
28
|
-
"from tqdm import tqdm\n",
|
|
29
|
-
"from wordllama import WordLlama"
|
|
30
|
-
]
|
|
31
|
-
},
|
|
32
|
-
{
|
|
33
|
-
"cell_type": "markdown",
|
|
34
|
-
"metadata": {},
|
|
35
|
-
"source": [
|
|
36
|
-
"**Loading data and model**\n",
|
|
37
|
-
"\n",
|
|
38
|
-
"We will use the AG News dataset and the Model2Vec pretrained model for deduplication."
|
|
39
|
-
]
|
|
40
|
-
},
|
|
41
|
-
{
|
|
42
|
-
"cell_type": "code",
|
|
43
|
-
"execution_count": 40,
|
|
44
|
-
"metadata": {},
|
|
45
|
-
"outputs": [],
|
|
46
|
-
"source": [
|
|
47
|
-
"# Load the model and dataset\n",
|
|
48
|
-
"model = StaticModel.from_pretrained(\"minishlab/M2V_base_output\")\n",
|
|
49
|
-
"ds = load_dataset(\"ag_news\")[\"train\"]\n",
|
|
50
|
-
"texts = ds['text']"
|
|
51
|
-
]
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
"cell_type": "markdown",
|
|
55
|
-
"metadata": {},
|
|
56
|
-
"source": [
|
|
57
|
-
"**Exact overlap baseline**\n",
|
|
58
|
-
"\n",
|
|
59
|
-
"We will first try to find exact matches in the dataset as a baseline."
|
|
60
|
-
]
|
|
61
|
-
},
|
|
62
|
-
{
|
|
63
|
-
"cell_type": "code",
|
|
64
|
-
"execution_count": 96,
|
|
65
|
-
"metadata": {},
|
|
66
|
-
"outputs": [
|
|
67
|
-
{
|
|
68
|
-
"name": "stdout",
|
|
69
|
-
"output_type": "stream",
|
|
70
|
-
"text": [
|
|
71
|
-
"Number of deduplicated docs: 120000\n"
|
|
72
|
-
]
|
|
73
|
-
}
|
|
74
|
-
],
|
|
75
|
-
"source": [
|
|
76
|
-
"seen = set()\n",
|
|
77
|
-
"deduplicated_text_indices = []\n",
|
|
78
|
-
"\n",
|
|
79
|
-
"for i, text in enumerate(texts):\n",
|
|
80
|
-
" if text not in seen:\n",
|
|
81
|
-
" deduplicated_text_indices.append(i)\n",
|
|
82
|
-
" seen.add(text)\n",
|
|
83
|
-
"\n",
|
|
84
|
-
"print(\"Number of deduplicated docs:\", len(deduplicated_text_indices))"
|
|
85
|
-
]
|
|
86
|
-
},
|
|
87
|
-
{
|
|
88
|
-
"cell_type": "markdown",
|
|
89
|
-
"metadata": {},
|
|
90
|
-
"source": [
|
|
91
|
-
"As can be seen, we find no duplicate instances using exact string matching. \n",
|
|
92
|
-
"\n",
|
|
93
|
-
"**Deduplication using Model2Vec**\n",
|
|
94
|
-
"\n",
|
|
95
|
-
"Let's now use Model2Vec to embed our documents and identify duplicates."
|
|
96
|
-
]
|
|
97
|
-
},
|
|
98
|
-
{
|
|
99
|
-
"cell_type": "code",
|
|
100
|
-
"execution_count": 41,
|
|
101
|
-
"metadata": {},
|
|
102
|
-
"outputs": [
|
|
103
|
-
{
|
|
104
|
-
"name": "stderr",
|
|
105
|
-
"output_type": "stream",
|
|
106
|
-
"text": [
|
|
107
|
-
"100%|██████████| 118/118 [00:02<00:00, 45.65it/s]\n"
|
|
108
|
-
]
|
|
109
|
-
}
|
|
110
|
-
],
|
|
111
|
-
"source": [
|
|
112
|
-
"# Encode texts into embeddings\n",
|
|
113
|
-
"embedding_matrix = model.encode(texts)"
|
|
114
|
-
]
|
|
115
|
-
},
|
|
116
|
-
{
|
|
117
|
-
"cell_type": "code",
|
|
118
|
-
"execution_count": 53,
|
|
119
|
-
"metadata": {},
|
|
120
|
-
"outputs": [],
|
|
121
|
-
"source": [
|
|
122
|
-
"def deduplicate(embedding_matrix: np.ndarray, threshold: float, batch_size: int = 1024) -> tuple[np.ndarray, dict[int, int]]:\n",
|
|
123
|
-
" \"\"\"\n",
|
|
124
|
-
" Deduplicate embeddings and return the deduplicated indices and a mapping of removed indices to their corresponding original indices.\n",
|
|
125
|
-
" \n",
|
|
126
|
-
" :param embedding_matrix: The embeddings to deduplicate.\n",
|
|
127
|
-
" :param threshold: The similarity threshold to use for deduplication.\n",
|
|
128
|
-
" :param batch_size: The batch size to use for similarity computation.\n",
|
|
129
|
-
" :return: A tuple containing the deduplicated indices and a dictionary mapping removed indices to original indices.\n",
|
|
130
|
-
" \"\"\"\n",
|
|
131
|
-
" reach = Reach(vectors=embedding_matrix, items=[str(i) for i in range(len(embedding_matrix))])\n",
|
|
132
|
-
" \n",
|
|
133
|
-
" # Use a set for deduplicated indices and keep track of duplicates\n",
|
|
134
|
-
" deduplicated_indices = set(range(len(embedding_matrix))) # Start with all indices as deduplicated\n",
|
|
135
|
-
" duplicate_to_original_mapping = {}\n",
|
|
136
|
-
"\n",
|
|
137
|
-
" results = reach.nearest_neighbor_threshold(\n",
|
|
138
|
-
" embedding_matrix, \n",
|
|
139
|
-
" threshold=threshold, \n",
|
|
140
|
-
" batch_size=batch_size, \n",
|
|
141
|
-
" show_progressbar=True\n",
|
|
142
|
-
" )\n",
|
|
143
|
-
" \n",
|
|
144
|
-
" # Process duplicates\n",
|
|
145
|
-
" for i, similar_items in enumerate(tqdm(results)):\n",
|
|
146
|
-
" if i not in deduplicated_indices:\n",
|
|
147
|
-
" continue # Skip already marked duplicates\n",
|
|
148
|
-
"\n",
|
|
149
|
-
" # Similar items are returned as (index, score), we are only interested in the index\n",
|
|
150
|
-
" similar_indices = [int(item[0]) for item in similar_items if int(item[0]) != i]\n",
|
|
151
|
-
" \n",
|
|
152
|
-
" # Mark similar documents as duplicates and map them to the original\n",
|
|
153
|
-
" for sim_idx in similar_indices:\n",
|
|
154
|
-
" if sim_idx in deduplicated_indices:\n",
|
|
155
|
-
" deduplicated_indices.remove(sim_idx)\n",
|
|
156
|
-
" duplicate_to_original_mapping[sim_idx] = i # Map duplicate to original\n",
|
|
157
|
-
"\n",
|
|
158
|
-
" return np.array(list(deduplicated_indices)), duplicate_to_original_mapping\n"
|
|
159
|
-
]
|
|
160
|
-
},
|
|
161
|
-
{
|
|
162
|
-
"cell_type": "code",
|
|
163
|
-
"execution_count": 81,
|
|
164
|
-
"metadata": {},
|
|
165
|
-
"outputs": [
|
|
166
|
-
{
|
|
167
|
-
"name": "stderr",
|
|
168
|
-
"output_type": "stream",
|
|
169
|
-
"text": [
|
|
170
|
-
"100%|██████████| 118/118 [00:25<00:00, 4.64it/s]\n",
|
|
171
|
-
"100%|██████████| 120000/120000 [00:00<00:00, 679800.97it/s]"
|
|
172
|
-
]
|
|
173
|
-
},
|
|
174
|
-
{
|
|
175
|
-
"name": "stdout",
|
|
176
|
-
"output_type": "stream",
|
|
177
|
-
"text": [
|
|
178
|
-
"Number of deduplicated docs: 118769\n"
|
|
179
|
-
]
|
|
180
|
-
},
|
|
181
|
-
{
|
|
182
|
-
"name": "stderr",
|
|
183
|
-
"output_type": "stream",
|
|
184
|
-
"text": [
|
|
185
|
-
"\n"
|
|
186
|
-
]
|
|
187
|
-
}
|
|
188
|
-
],
|
|
189
|
-
"source": [
|
|
190
|
-
"# Deduplicate (with a high threshold)\n",
|
|
191
|
-
"deduplicated_indices, duplicate_to_original_mapping = deduplicate(embedding_matrix, threshold=0.99)\n",
|
|
192
|
-
"print(f\"Number of deduplicated docs: {len(deduplicated_indices)}\")"
|
|
193
|
-
]
|
|
194
|
-
},
|
|
195
|
-
{
|
|
196
|
-
"cell_type": "markdown",
|
|
197
|
-
"metadata": {},
|
|
198
|
-
"source": [
|
|
199
|
-
"Using Model2Vec, we find > 1000 duplicates with a very high threshold, in < 30 seconds. Now, let's look at a few examples to see if these are indeed duplicates."
|
|
200
|
-
]
|
|
201
|
-
},
|
|
202
|
-
{
|
|
203
|
-
"cell_type": "code",
|
|
204
|
-
"execution_count": 71,
|
|
205
|
-
"metadata": {},
|
|
206
|
-
"outputs": [
|
|
207
|
-
{
|
|
208
|
-
"name": "stdout",
|
|
209
|
-
"output_type": "stream",
|
|
210
|
-
"text": [
|
|
211
|
-
"Original text:\n",
|
|
212
|
-
"Oil and Economy Cloud Stocks' Outlook (Reuters) Reuters - Soaring crude prices plus worries\\about the economy and the outlook for earnings are expected to\\hang over the stock market next week during the depth of the\\summer doldrums.\n",
|
|
213
|
-
"Duplicate text:\n",
|
|
214
|
-
"Oil and Economy Cloud Stocks' Outlook (Reuters) Reuters - Soaring crude prices plus worries\\about the economy and the outlook for earnings are expected to\\hang over the stock market this week during the depth of the\\summer doldrums.\n",
|
|
215
|
-
"Differences:\n",
|
|
216
|
-
"- next + this\n",
|
|
217
|
-
"--------------------------------------------------\n",
|
|
218
|
-
"Original text:\n",
|
|
219
|
-
"Oil and Economy Cloud Stocks' Outlook NEW YORK (Reuters) - Soaring crude prices plus worries about the economy and the outlook for earnings are expected to hang over the stock market next week during the depth of the summer doldrums.\n",
|
|
220
|
-
"Duplicate text:\n",
|
|
221
|
-
"Oil and Economy Cloud Stocks' Outlook NEW YORK (Reuters) - Soaring crude prices plus worries about the economy and the outlook for earnings are expected to hang over the stock market this week during the depth of the summer doldrums.\n",
|
|
222
|
-
"Differences:\n",
|
|
223
|
-
"- next + this\n",
|
|
224
|
-
"--------------------------------------------------\n",
|
|
225
|
-
"Original text:\n",
|
|
226
|
-
"Phelps, Thorpe Advance in 200 Freestyle ATHENS, Greece - Michael Phelps took care of qualifying for the Olympic 200-meter freestyle semifinals Sunday, and then found out he had been added to the American team for the evening's 400 freestyle relay final. Phelps' rivals Ian Thorpe and Pieter van den Hoogenband and teammate Klete Keller were faster than the teenager in the 200 free preliminaries...\n",
|
|
227
|
-
"Duplicate text:\n",
|
|
228
|
-
"Phelps, Thorpe Advance in 200 Freestyle ATHENS, Greece - Michael Phelps took care of qualifying for the Olympic 200-meter freestyle semifinals Sunday, and then found out he had been added to the American team for the evening's 400 freestyle relay final. Phelps' rivals Ian Thorpe and Pieter van den Hoogenband and teammate Klete Keller were faster than the teenager in the 200 free preliminaries...\n",
|
|
229
|
-
"Differences:\n",
|
|
230
|
-
"\n",
|
|
231
|
-
"--------------------------------------------------\n",
|
|
232
|
-
"Original text:\n",
|
|
233
|
-
"Government Spending Up Sharply Locally Federal procurement spending in the Washington area rose last year at its highest rate since the 1980s, according to a study to be released today, creating tens of thousands of jobs and increasing economic growth disproportionately in Northern Virginia.\n",
|
|
234
|
-
"Duplicate text:\n",
|
|
235
|
-
"Government Spending Up Sharply Locally Federal procurement spending in the Washington area rose last year at its highest rate since the 1980s, according to a study to be released today, creating tens of thousands of jobs and increasing economic growth disproportionately in Northern Virginia.\n",
|
|
236
|
-
"Differences:\n",
|
|
237
|
-
"\n",
|
|
238
|
-
"--------------------------------------------------\n",
|
|
239
|
-
"Original text:\n",
|
|
240
|
-
"F.B.I. Goes Knocking for Political Troublemakers The F.B.I. has been questioning demonstrators in an effort to forestall violent protests at the Republican National Convention.\n",
|
|
241
|
-
"Duplicate text:\n",
|
|
242
|
-
"F.B.I. Goes Knocking for Political Troublemakers The F.B.I. has been questioning demonstrators in an effort to forestall violent protests at the Republican convention.\n",
|
|
243
|
-
"Differences:\n",
|
|
244
|
-
"- National - Convention. + convention.\n",
|
|
245
|
-
"--------------------------------------------------\n"
|
|
246
|
-
]
|
|
247
|
-
}
|
|
248
|
-
],
|
|
249
|
-
"source": [
|
|
250
|
-
"def display_word_differences(x: str, y: str) -> str:\n",
|
|
251
|
-
" diff = ndiff(x.split(), y.split())\n",
|
|
252
|
-
" return \" \".join([f\"{word}\" for word in diff if word.startswith(('+', '-'))])\n",
|
|
253
|
-
"\n",
|
|
254
|
-
"# Show a few duplicates with their originals, highlighting word-level differences\n",
|
|
255
|
-
"num_examples = 5\n",
|
|
256
|
-
"for duplicate_idx, original_idx in list(duplicate_to_original_mapping.items())[:num_examples]:\n",
|
|
257
|
-
" print(f\"Original text:\\n{texts[original_idx]}\")\n",
|
|
258
|
-
" print(f\"Duplicate text:\\n{texts[duplicate_idx]}\")\n",
|
|
259
|
-
" print(\"Differences:\")\n",
|
|
260
|
-
" print(display_word_differences(texts[original_idx], texts[duplicate_idx]))\n",
|
|
261
|
-
" print(\"-\" * 50)\n"
|
|
262
|
-
]
|
|
263
|
-
},
|
|
264
|
-
{
|
|
265
|
-
"cell_type": "markdown",
|
|
266
|
-
"metadata": {},
|
|
267
|
-
"source": [
|
|
268
|
-
"The found texts do indeed seem to be duplicates, nice! In a normal workflow where we use Model2Vec to embed our documents, deduplication our training corpus is essentially free. This gives us an easy to use, easy to integrate, fast way to deduplicate.\n",
|
|
269
|
-
"\n",
|
|
270
|
-
"**Deduplication using WordLlama**\n",
|
|
271
|
-
"\n",
|
|
272
|
-
"For comparison, let's also try a different library (WordLlama), which also uses static embeddings to deduplicate text data."
|
|
273
|
-
]
|
|
274
|
-
},
|
|
275
|
-
{
|
|
276
|
-
"cell_type": "code",
|
|
277
|
-
"execution_count": 84,
|
|
278
|
-
"metadata": {},
|
|
279
|
-
"outputs": [
|
|
280
|
-
{
|
|
281
|
-
"name": "stdout",
|
|
282
|
-
"output_type": "stream",
|
|
283
|
-
"text": [
|
|
284
|
-
"Number of deduplicated docs: 119128\n",
|
|
285
|
-
"Time taken: 42.821428374998504\n"
|
|
286
|
-
]
|
|
287
|
-
}
|
|
288
|
-
],
|
|
289
|
-
"source": [
|
|
290
|
-
"wl = WordLlama.load()\n",
|
|
291
|
-
"\n",
|
|
292
|
-
"time = perf_counter()\n",
|
|
293
|
-
"deduplicated_docs = wl.deduplicate(texts, threshold=0.99)\n",
|
|
294
|
-
"print(f\"Number of deduplicated docs: {len(deduplicated_docs)}\")\n",
|
|
295
|
-
"print(f\"Time taken: {perf_counter() - time}\")\n"
|
|
296
|
-
]
|
|
297
|
-
},
|
|
298
|
-
{
|
|
299
|
-
"cell_type": "markdown",
|
|
300
|
-
"metadata": {},
|
|
301
|
-
"source": [
|
|
302
|
-
"This approach is considerably slower than Model2Vec for encoding + deduplication (43 vs 27 seconds). It also finds less duplicates with the same threshold.\n",
|
|
303
|
-
"\n",
|
|
304
|
-
"**Deduplication using MinHash**\n",
|
|
305
|
-
"\n",
|
|
306
|
-
"As a last comparison, let's use MinHash, a common method for deduplication. We will use the datasketch library to find duplicates."
|
|
307
|
-
]
|
|
308
|
-
},
|
|
309
|
-
{
|
|
310
|
-
"cell_type": "code",
|
|
311
|
-
"execution_count": 77,
|
|
312
|
-
"metadata": {},
|
|
313
|
-
"outputs": [
|
|
314
|
-
{
|
|
315
|
-
"name": "stdout",
|
|
316
|
-
"output_type": "stream",
|
|
317
|
-
"text": [
|
|
318
|
-
"Number of deduplicated docs: 118653\n",
|
|
319
|
-
"Time taken: 56.46521229199425\n"
|
|
320
|
-
]
|
|
321
|
-
}
|
|
322
|
-
],
|
|
323
|
-
"source": [
|
|
324
|
-
"def get_minhash(text: str, num_perm: int = 128) -> MinHash:\n",
|
|
325
|
-
" m = MinHash(num_perm=num_perm)\n",
|
|
326
|
-
" for word in text.split():\n",
|
|
327
|
-
" m.update(word.encode('utf8'))\n",
|
|
328
|
-
" return m\n",
|
|
329
|
-
"\n",
|
|
330
|
-
"def deduplicate_with_minhash(texts: list[str], threshold: float = 0.9) -> list[int]:\n",
|
|
331
|
-
" \"\"\"\n",
|
|
332
|
-
" Deduplicate texts using MinHash and return the indices of unique texts.\n",
|
|
333
|
-
"\n",
|
|
334
|
-
" :param texts: List of texts to deduplicate.\n",
|
|
335
|
-
" :param threshold: Jaccard similarity threshold for considering texts as duplicates.\n",
|
|
336
|
-
" :return: List of indices of deduplicated texts.\n",
|
|
337
|
-
" \"\"\"\n",
|
|
338
|
-
" lsh = MinHashLSH(threshold=threshold)\n",
|
|
339
|
-
" deduplicated_text_indices = []\n",
|
|
340
|
-
"\n",
|
|
341
|
-
" for i, text in enumerate(texts):\n",
|
|
342
|
-
" # Generate MinHash for the current text\n",
|
|
343
|
-
" minhash = get_minhash(text)\n",
|
|
344
|
-
"\n",
|
|
345
|
-
" # Check if the MinHash is already in the LSH (i.e., if it is a duplicate)\n",
|
|
346
|
-
" if not lsh.query(minhash):\n",
|
|
347
|
-
" # If it's not a duplicate, add the MinHash and keep the index\n",
|
|
348
|
-
" deduplicated_text_indices.append(i)\n",
|
|
349
|
-
" lsh.insert(i, minhash)\n",
|
|
350
|
-
"\n",
|
|
351
|
-
" return deduplicated_text_indices\n",
|
|
352
|
-
"\n",
|
|
353
|
-
"\n",
|
|
354
|
-
"time = perf_counter()\n",
|
|
355
|
-
"deduplicated_text_indices = deduplicate_with_minhash(texts)\n",
|
|
356
|
-
"print(f\"Number of deduplicated docs: {len(deduplicated_text_indices)}\")\n",
|
|
357
|
-
"print(f\"Time taken: {perf_counter() - time}\")\n"
|
|
358
|
-
]
|
|
359
|
-
},
|
|
360
|
-
{
|
|
361
|
-
"cell_type": "markdown",
|
|
362
|
-
"metadata": {},
|
|
363
|
-
"source": [
|
|
364
|
-
"Model2Vec is again much faster, with 27 seconds vs 56 seconds for MinHash. The number of found duplicates is roughly the same using the default settings for MinHash.\n",
|
|
365
|
-
"\n",
|
|
366
|
-
"**Train test leakage detection using Model2Vec**\n",
|
|
367
|
-
"\n",
|
|
368
|
-
"Now, as a last experiment, let's also embed the test set, and see if there are any duplicates between the training and test set. This is a common issue in NLP, where the test set may contain instances that are also in the training set.\n"
|
|
369
|
-
]
|
|
370
|
-
},
|
|
371
|
-
{
|
|
372
|
-
"cell_type": "code",
|
|
373
|
-
"execution_count": 90,
|
|
374
|
-
"metadata": {},
|
|
375
|
-
"outputs": [
|
|
376
|
-
{
|
|
377
|
-
"name": "stderr",
|
|
378
|
-
"output_type": "stream",
|
|
379
|
-
"text": [
|
|
380
|
-
"100%|██████████| 118/118 [00:02<00:00, 45.36it/s]\n",
|
|
381
|
-
"100%|██████████| 8/8 [00:00<00:00, 51.05it/s]\n",
|
|
382
|
-
"100%|██████████| 8/8 [00:01<00:00, 5.40it/s]\n",
|
|
383
|
-
"100%|██████████| 7600/7600 [00:00<00:00, 901108.42it/s]"
|
|
384
|
-
]
|
|
385
|
-
},
|
|
386
|
-
{
|
|
387
|
-
"name": "stdout",
|
|
388
|
-
"output_type": "stream",
|
|
389
|
-
"text": [
|
|
390
|
-
"Number of duplicates found between train and test: 138\n"
|
|
391
|
-
]
|
|
392
|
-
},
|
|
393
|
-
{
|
|
394
|
-
"name": "stderr",
|
|
395
|
-
"output_type": "stream",
|
|
396
|
-
"text": [
|
|
397
|
-
"\n"
|
|
398
|
-
]
|
|
399
|
-
}
|
|
400
|
-
],
|
|
401
|
-
"source": [
|
|
402
|
-
"# Load the datasets\n",
|
|
403
|
-
"ds_train = load_dataset(\"ag_news\")[\"train\"]\n",
|
|
404
|
-
"ds_test = load_dataset(\"ag_news\")[\"test\"]\n",
|
|
405
|
-
"\n",
|
|
406
|
-
"texts_train = ds_train['text']\n",
|
|
407
|
-
"texts_test = ds_test['text']\n",
|
|
408
|
-
"\n",
|
|
409
|
-
"# Encode texts into embeddings\n",
|
|
410
|
-
"embedding_matrix_train = model.encode(texts_train)\n",
|
|
411
|
-
"embedding_matrix_test = model.encode(texts_test)\n",
|
|
412
|
-
"\n",
|
|
413
|
-
"def deduplicate_across_datasets(embedding_matrix_1: np.ndarray, embedding_matrix_2: np.ndarray, threshold: float, batch_size: int = 1024) -> tuple[list[int], dict[int, int]]:\n",
|
|
414
|
-
" \"\"\"\n",
|
|
415
|
-
" Deduplicate embeddings across two datasets and return the indices of duplicates between them.\n",
|
|
416
|
-
" \n",
|
|
417
|
-
" :param embedding_matrix_1: The embeddings of the first dataset (e.g., train).\n",
|
|
418
|
-
" :param embedding_matrix_2: The embeddings of the second dataset (e.g., test).\n",
|
|
419
|
-
" :param threshold: The similarity threshold to use for deduplication.\n",
|
|
420
|
-
" :param batch_size: The batch size to use for similarity computation.\n",
|
|
421
|
-
" :return: A tuple containing the duplicate indices and a dictionary mapping removed indices in the second dataset to their corresponding indices in the first dataset.\n",
|
|
422
|
-
" \"\"\"\n",
|
|
423
|
-
" reach = Reach(vectors=embedding_matrix_1, items=[str(i) for i in range(len(embedding_matrix_1))])\n",
|
|
424
|
-
"\n",
|
|
425
|
-
" # Keep track of duplicates in the second dataset\n",
|
|
426
|
-
" duplicate_indices_in_test = []\n",
|
|
427
|
-
" duplicate_to_original_mapping = {}\n",
|
|
428
|
-
"\n",
|
|
429
|
-
" # Find nearest neighbors from the test set in the train set\n",
|
|
430
|
-
" results = reach.nearest_neighbor_threshold(\n",
|
|
431
|
-
" embedding_matrix_2, \n",
|
|
432
|
-
" threshold=threshold, \n",
|
|
433
|
-
" batch_size=batch_size, \n",
|
|
434
|
-
" show_progressbar=True\n",
|
|
435
|
-
" )\n",
|
|
436
|
-
" \n",
|
|
437
|
-
" # Process duplicates\n",
|
|
438
|
-
" for i, similar_items in enumerate(tqdm(results)):\n",
|
|
439
|
-
" # Similar items are returned as (index, score), we are only interested in the index\n",
|
|
440
|
-
" similar_indices = [int(item[0]) for item in similar_items if item[1] >= threshold] # Keep those above the threshold\n",
|
|
441
|
-
" \n",
|
|
442
|
-
" # If we find a similar item in the train set, mark it as a duplicate\n",
|
|
443
|
-
" if similar_indices:\n",
|
|
444
|
-
" duplicate_indices_in_test.append(i)\n",
|
|
445
|
-
" duplicate_to_original_mapping[i] = similar_indices[0] # Map duplicate in test to original in train\n",
|
|
446
|
-
"\n",
|
|
447
|
-
" return duplicate_indices_in_test, duplicate_to_original_mapping\n",
|
|
448
|
-
"\n",
|
|
449
|
-
"# Check for train/test bleed\n",
|
|
450
|
-
"duplicate_indices_in_test, duplicate_to_original_mapping = deduplicate_across_datasets(\n",
|
|
451
|
-
" embedding_matrix_train, \n",
|
|
452
|
-
" embedding_matrix_test, \n",
|
|
453
|
-
" threshold=0.99 # High threshold for deduplication\n",
|
|
454
|
-
")\n",
|
|
455
|
-
"\n",
|
|
456
|
-
"print(f\"Number of duplicates found between train and test: {len(duplicate_indices_in_test)}\")\n"
|
|
457
|
-
]
|
|
458
|
-
},
|
|
459
|
-
{
|
|
460
|
-
"cell_type": "code",
|
|
461
|
-
"execution_count": 99,
|
|
462
|
-
"metadata": {},
|
|
463
|
-
"outputs": [
|
|
464
|
-
{
|
|
465
|
-
"name": "stdout",
|
|
466
|
-
"output_type": "stream",
|
|
467
|
-
"text": [
|
|
468
|
-
"Train text:\n",
|
|
469
|
-
"Jackson Squares Off With Attorney SANTA MARIA, Calif. - Fans of Michael Jackson erupted in cheers Monday as the pop star emerged from a double-decker tour bus and went into court for a showdown with the prosecutor who has pursued him for years on child molestation charges...\n",
|
|
470
|
-
"Test text:\n",
|
|
471
|
-
"Jackson Squares Off With Prosecutor SANTA MARIA, Calif. - Fans of Michael Jackson erupted in cheers Monday as the pop star emerged from a double-decker tour bus and went into court for a showdown with the prosecutor who has pursued him for years on child molestation charges...\n",
|
|
472
|
-
"Differences:\n",
|
|
473
|
-
"- Attorney + Prosecutor\n",
|
|
474
|
-
"--------------------------------------------------\n",
|
|
475
|
-
"Train text:\n",
|
|
476
|
-
"Cassini Spies Two Moons Around Saturn (AP) AP - NASA's Cassini spacecraft has spied two new little moons around satellite-rich Saturn, the space agency said.\n",
|
|
477
|
-
"Test text:\n",
|
|
478
|
-
"Cassini Spies Two Little Saturn Moons (AP) AP - NASA's Cassini spacecraft has spied two new little moons around satellite-rich Saturn, the space agency said Monday.\n",
|
|
479
|
-
"Differences:\n",
|
|
480
|
-
"+ Little + Saturn - Around - Saturn - said. + said + Monday.\n",
|
|
481
|
-
"--------------------------------------------------\n",
|
|
482
|
-
"Train text:\n",
|
|
483
|
-
"Intel to Delay Product for High-Definition TVs SAN FRANCISCO (Reuters) - In the latest of a series of product delays, Intel Corp. has postponed the launch of a video display chip it had previously planned to introduce by year end, putting off a showdown with Texas Instruments Inc. in the fast-growing market for high-definition television displays.\n",
|
|
484
|
-
"Test text:\n",
|
|
485
|
-
"Intel to delay product aimed for high-definition TVs SAN FRANCISCO -- In the latest of a series of product delays, Intel Corp. has postponed the launch of a video display chip it had previously planned to introduce by year end, putting off a showdown with Texas Instruments Inc. in the fast-growing market for high-definition television displays.\n",
|
|
486
|
-
"Differences:\n",
|
|
487
|
-
"- Delay + delay - Product + product + aimed - High-Definition + high-definition + -- - (Reuters) - -\n",
|
|
488
|
-
"--------------------------------------------------\n",
|
|
489
|
-
"Train text:\n",
|
|
490
|
-
"Staples Profit Up Sharply, to Enter China NEW YORK (Reuters) - Staples Inc. <A HREF=\"http://www.investor.reuters.com/FullQuote.aspx?ticker=SPLS.O target=/stocks/quickinfo/fullquote\">SPLS.O</A>, the top U.S. office products retailer, on Tuesday reported a 39 percent jump in quarterly profit, raised its full-year forecast and said it plans to enter the fast-growing Chinese market.\n",
|
|
491
|
-
"Test text:\n",
|
|
492
|
-
"Staples Profit Up, to Enter China Market NEW YORK (Reuters) - Staples Inc. <A HREF=\"http://www.investor.reuters.com/FullQuote.aspx?ticker=SPLS.O target=/stocks/quickinfo/fullquote\">SPLS.O</A>, the top U.S. office products retailer, on Tuesday reported a 39 percent jump in quarterly profit, raised its full-year forecast and said it plans to enter the fast-growing Chinese market, sending its shares higher.\n",
|
|
493
|
-
"Differences:\n",
|
|
494
|
-
"- Up + Up, - Sharply, + Market - market. + market, + sending + its + shares + higher.\n",
|
|
495
|
-
"--------------------------------------------------\n",
|
|
496
|
-
"Train text:\n",
|
|
497
|
-
"Stocks Climb on Drop in Consumer Prices NEW YORK - Stocks rose for a second straight session Tuesday as a drop in consumer prices Tuesday allowed investors to put aside worries about inflation, at least for the short term. With gasoline prices falling to eight-month lows, the Consumer Price Index registered a small drop in July, giving consumers a respite from soaring energy prices...\n",
|
|
498
|
-
"Test text:\n",
|
|
499
|
-
"Stocks Climb on Drop in Consumer Prices NEW YORK - Stocks rose for a second straight session Tuesday as a drop in consumer prices allowed investors to put aside worries about inflation, at least for the short term. With gasoline prices falling to eight-month lows, the Consumer Price Index registered a small drop in July, giving consumers a respite from soaring energy prices...\n",
|
|
500
|
-
"Differences:\n",
|
|
501
|
-
"- Tuesday\n",
|
|
502
|
-
"--------------------------------------------------\n"
|
|
503
|
-
]
|
|
504
|
-
}
|
|
505
|
-
],
|
|
506
|
-
"source": [
|
|
507
|
-
"# Show a few duplicates with their originals, highlighting word-level differences\n",
|
|
508
|
-
"num_examples = 5\n",
|
|
509
|
-
"for i, test_idx in enumerate(duplicate_indices_in_test[:num_examples]):\n",
|
|
510
|
-
" train_idx = duplicate_to_original_mapping[test_idx]\n",
|
|
511
|
-
"\n",
|
|
512
|
-
" print(f\"Train text:\\n{texts_train[train_idx]}\")\n",
|
|
513
|
-
" print(f\"Test text:\\n{texts_test[test_idx]}\")\n",
|
|
514
|
-
" print(\"Differences:\")\n",
|
|
515
|
-
" print(display_word_differences(texts_train[train_idx], texts_test[test_idx]))\n",
|
|
516
|
-
" print(\"-\" * 50)\n"
|
|
517
|
-
]
|
|
518
|
-
},
|
|
519
|
-
{
|
|
520
|
-
"cell_type": "markdown",
|
|
521
|
-
"metadata": {},
|
|
522
|
-
"source": [
|
|
523
|
-
"These again look like duplicates. We can very efficiently find train/test leakage examples using Model2Vec, ensuring that our test set is clean and does not contain any duplicates from the training set.\n",
|
|
524
|
-
"\n",
|
|
525
|
-
"**Conclusion**\n",
|
|
526
|
-
"\n",
|
|
527
|
-
"Model2Vec provides an efficient and fast solution for semantic deduplication, outperforming other methods like WordLlama and MinHash in terms of speed. Additionally, its ability to detect train-test overlap makes it a valuable tool for preparing clean datasets for machine learning tasks."
|
|
528
|
-
]
|
|
529
|
-
}
|
|
530
|
-
],
|
|
531
|
-
"metadata": {
|
|
532
|
-
"kernelspec": {
|
|
533
|
-
"display_name": "venv",
|
|
534
|
-
"language": "python",
|
|
535
|
-
"name": "python3"
|
|
536
|
-
},
|
|
537
|
-
"language_info": {
|
|
538
|
-
"codemirror_mode": {
|
|
539
|
-
"name": "ipython",
|
|
540
|
-
"version": 3
|
|
541
|
-
},
|
|
542
|
-
"file_extension": ".py",
|
|
543
|
-
"mimetype": "text/x-python",
|
|
544
|
-
"name": "python",
|
|
545
|
-
"nbconvert_exporter": "python",
|
|
546
|
-
"pygments_lexer": "ipython3",
|
|
547
|
-
"version": "3.10.11"
|
|
548
|
-
}
|
|
549
|
-
},
|
|
550
|
-
"nbformat": 4,
|
|
551
|
-
"nbformat_minor": 2
|
|
552
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{model2vec-0.3.7 → model2vec-0.3.8}/assets/images/model2vec_model_diagram_transparant_dark.png
RENAMED
|
File without changes
|
{model2vec-0.3.7 → model2vec-0.3.8}/assets/images/model2vec_model_diagram_transparant_light.png
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|