semhash 0.1.0__py3-none-any.whl
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.
- semhash/__init__.py +3 -0
- semhash/semhash.py +185 -0
- semhash/utils.py +21 -0
- semhash/version.py +2 -0
- semhash-0.1.0.dist-info/LICENSE +21 -0
- semhash-0.1.0.dist-info/METADATA +277 -0
- semhash-0.1.0.dist-info/RECORD +9 -0
- semhash-0.1.0.dist-info/WHEEL +5 -0
- semhash-0.1.0.dist-info/top_level.txt +1 -0
semhash/__init__.py
ADDED
semhash/semhash.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Sequence, Union, cast
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from model2vec import StaticModel
|
|
7
|
+
from vicinity import Backend, Vicinity
|
|
8
|
+
|
|
9
|
+
from semhash.utils import Encoder
|
|
10
|
+
|
|
11
|
+
Record = Union[str, dict[str, str]]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SemHash:
|
|
15
|
+
def __init__(self, model: Encoder | None = None, columns: list[str] | None = None, ann: bool = False) -> None:
|
|
16
|
+
"""
|
|
17
|
+
Initialize SemHash.
|
|
18
|
+
|
|
19
|
+
:param model: A model to use for featurization. Defaults to minishlab/potion-base-8M.
|
|
20
|
+
:param columns: Columns to featurize. Required if records are dictionaries.
|
|
21
|
+
:param ann: Whether to use approximate nearest neighbors for deduplication. Default is False.
|
|
22
|
+
"""
|
|
23
|
+
self.model = model if model else StaticModel.from_pretrained("minishlab/potion-base-8M")
|
|
24
|
+
self.backend = Backend.USEARCH if ann else Backend.BASIC
|
|
25
|
+
self.columns = columns
|
|
26
|
+
self.vicinity: Vicinity | None = None
|
|
27
|
+
|
|
28
|
+
def _featurize(self, records: Sequence[Record]) -> np.ndarray:
|
|
29
|
+
"""
|
|
30
|
+
Featurize a list of records using the model.
|
|
31
|
+
|
|
32
|
+
:param records: A list of records (either strings or dictionaries).
|
|
33
|
+
:return: The embeddings of the records.
|
|
34
|
+
:raises ValueError: If columns are not specified when passing dictionaries.
|
|
35
|
+
"""
|
|
36
|
+
if isinstance(records[0], dict):
|
|
37
|
+
if self.columns is None:
|
|
38
|
+
raise ValueError("Columns must be specified when passing dictionaries.")
|
|
39
|
+
|
|
40
|
+
records = cast(Sequence[dict[str, str]], records)
|
|
41
|
+
# Extract the embeddings for each column across all records
|
|
42
|
+
embeddings_per_column = []
|
|
43
|
+
for column in self.columns:
|
|
44
|
+
column_texts = [r[column] for r in records]
|
|
45
|
+
column_embeddings = self.model.encode(column_texts)
|
|
46
|
+
embeddings_per_column.append(np.asarray(column_embeddings))
|
|
47
|
+
|
|
48
|
+
return np.concatenate(embeddings_per_column, axis=1)
|
|
49
|
+
|
|
50
|
+
else:
|
|
51
|
+
# Records is a list of strings
|
|
52
|
+
records = cast(Sequence[str], records)
|
|
53
|
+
embeddings = self.model.encode(records)
|
|
54
|
+
return embeddings
|
|
55
|
+
|
|
56
|
+
def _unpack_record(self, record: Record) -> str:
|
|
57
|
+
r"""
|
|
58
|
+
Unpack a record into a single string.
|
|
59
|
+
|
|
60
|
+
If the record is a dictionary, it uses self.columns to determine the order of the text segments.
|
|
61
|
+
Each text is cleaned by replacing '\t' with ' '. The texts are then joined by '\t'.
|
|
62
|
+
|
|
63
|
+
If the record is a string, it just replaces '\t' with ' ' and returns it.
|
|
64
|
+
"""
|
|
65
|
+
if isinstance(record, dict):
|
|
66
|
+
if self.columns is None:
|
|
67
|
+
raise ValueError("Columns must be specified when passing dictionaries.")
|
|
68
|
+
|
|
69
|
+
column_texts = []
|
|
70
|
+
for column in self.columns:
|
|
71
|
+
text = record[column].replace("\t", " ")
|
|
72
|
+
column_texts.append(text)
|
|
73
|
+
return "\t".join(column_texts)
|
|
74
|
+
else:
|
|
75
|
+
# Record is a string
|
|
76
|
+
return record.replace("\t", " ")
|
|
77
|
+
|
|
78
|
+
def _remove_exact_duplicates(self, records: Sequence[Record]) -> list[Record]:
|
|
79
|
+
"""
|
|
80
|
+
Remove exact duplicates based on the unpacked string representation of each record.
|
|
81
|
+
|
|
82
|
+
:param records: A list of records.
|
|
83
|
+
:return: A list of deduplicated records.
|
|
84
|
+
"""
|
|
85
|
+
seen = set()
|
|
86
|
+
deduplicated = []
|
|
87
|
+
for record in records:
|
|
88
|
+
unpacked = self._unpack_record(record)
|
|
89
|
+
if unpacked not in seen:
|
|
90
|
+
seen.add(unpacked)
|
|
91
|
+
deduplicated.append(record)
|
|
92
|
+
return deduplicated
|
|
93
|
+
|
|
94
|
+
def fit(self, records: Sequence[Record]) -> np.ndarray:
|
|
95
|
+
"""
|
|
96
|
+
Embed the records and fit a vicinity index on the embeddings.
|
|
97
|
+
|
|
98
|
+
:param records: The dataset to fit on. Can be a list of dictionaries or a list of strings.
|
|
99
|
+
:return: The embeddings of the records.
|
|
100
|
+
:raises ValueError: If columns are not specified when records are dictionaries.
|
|
101
|
+
"""
|
|
102
|
+
if self.columns is None and isinstance(records[0], dict):
|
|
103
|
+
raise ValueError("Columns must be specified when passing dictionaries.")
|
|
104
|
+
|
|
105
|
+
# Remove exact duplicates before embedding
|
|
106
|
+
records = self._remove_exact_duplicates(records)
|
|
107
|
+
|
|
108
|
+
# Compute embeddings for the records and unpack the records
|
|
109
|
+
embeddings = self._featurize(records)
|
|
110
|
+
items = [self._unpack_record(record) for record in records]
|
|
111
|
+
# Fit the index
|
|
112
|
+
self.vicinity = Vicinity.from_vectors_and_items(vectors=embeddings, items=items, backend_type=self.backend)
|
|
113
|
+
return embeddings
|
|
114
|
+
|
|
115
|
+
def deduplicate(
|
|
116
|
+
self,
|
|
117
|
+
records: Sequence[Record],
|
|
118
|
+
threshold: float = 0.9,
|
|
119
|
+
) -> Sequence[Record]:
|
|
120
|
+
"""
|
|
121
|
+
Perform deduplication against the fitted index.
|
|
122
|
+
|
|
123
|
+
This method assumes you have already fit on a reference dataset (e.g., a train set).
|
|
124
|
+
It will remove any items from 'records' that are similar above a certain threshold
|
|
125
|
+
to any item in the fitted dataset.
|
|
126
|
+
|
|
127
|
+
:param records: A new set of records (e.g., test set) to deduplicate against the fitted dataset.
|
|
128
|
+
:param threshold: Similarity threshold for deduplication.
|
|
129
|
+
:return: A deduplicated list of records.
|
|
130
|
+
:raises ValueError: If no fitted index is found.
|
|
131
|
+
"""
|
|
132
|
+
if self.vicinity is None:
|
|
133
|
+
raise ValueError("No fitted index found. Call semhash.fit(records) before calling deduplicate.")
|
|
134
|
+
|
|
135
|
+
# Compute embeddings for the new records
|
|
136
|
+
embeddings = self._featurize(records)
|
|
137
|
+
|
|
138
|
+
# Query the fitted index
|
|
139
|
+
results = self.vicinity.query_threshold(embeddings, threshold=1 - threshold)
|
|
140
|
+
|
|
141
|
+
# Keep only those records for which no similar item was found
|
|
142
|
+
deduplicated_records = []
|
|
143
|
+
for record, similar_items in zip(records, results):
|
|
144
|
+
if not similar_items:
|
|
145
|
+
# No duplicates found, keep this record
|
|
146
|
+
deduplicated_records.append(record)
|
|
147
|
+
|
|
148
|
+
return deduplicated_records
|
|
149
|
+
|
|
150
|
+
def fit_deduplicate(
|
|
151
|
+
self,
|
|
152
|
+
records: Sequence[Record],
|
|
153
|
+
threshold: float = 0.9,
|
|
154
|
+
) -> Sequence[Record]:
|
|
155
|
+
"""
|
|
156
|
+
Fit and deduplicate a single dataset.
|
|
157
|
+
|
|
158
|
+
This method removes any items that have duplicates within the same dataset.
|
|
159
|
+
|
|
160
|
+
:param records: The dataset to fit and deduplicate.
|
|
161
|
+
:param threshold: Similarity threshold for deduplication.
|
|
162
|
+
:return: A deduplicated list of records.
|
|
163
|
+
"""
|
|
164
|
+
# Remove exact duplicates before embedding
|
|
165
|
+
records = self._remove_exact_duplicates(records)
|
|
166
|
+
# Create embeddings and fit the index
|
|
167
|
+
embeddings = self.fit(records)
|
|
168
|
+
|
|
169
|
+
# Get similar items for each record
|
|
170
|
+
results = self.vicinity.query_threshold(embeddings, threshold=1 - threshold) # type: ignore
|
|
171
|
+
|
|
172
|
+
deduplicated_records = []
|
|
173
|
+
seen_items = set()
|
|
174
|
+
for record, similar_items in zip(records, results):
|
|
175
|
+
# similar_items includes 'record' itself
|
|
176
|
+
# If we've seen any of these items before, this is a duplicate cluster.
|
|
177
|
+
if any(item in seen_items for item in similar_items):
|
|
178
|
+
continue
|
|
179
|
+
else:
|
|
180
|
+
# This is the first time we see this cluster of similar items
|
|
181
|
+
deduplicated_records.append(record)
|
|
182
|
+
# Mark all items in this cluster as seen
|
|
183
|
+
seen_items.update(similar_items)
|
|
184
|
+
|
|
185
|
+
return deduplicated_records
|
semhash/utils.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from typing import Any, Protocol, Sequence
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Encoder(Protocol):
|
|
7
|
+
"""An encoder protocol for SemHash."""
|
|
8
|
+
|
|
9
|
+
def encode(
|
|
10
|
+
self,
|
|
11
|
+
sentences: list[str] | str | Sequence[str],
|
|
12
|
+
**kwargs: Any,
|
|
13
|
+
) -> np.ndarray:
|
|
14
|
+
"""
|
|
15
|
+
Encode a list of sentences into embeddings.
|
|
16
|
+
|
|
17
|
+
:param sentences: A list of sentences to encode.
|
|
18
|
+
:param **kwargs: Additional keyword arguments.
|
|
19
|
+
:return: The embeddings of the sentences.
|
|
20
|
+
"""
|
|
21
|
+
...
|
semhash/version.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 The Minish Lab
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: semhash
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fast Semantic Text Deduplication
|
|
5
|
+
Author-email: Thomas van Dongen <thomas123@live.nl>, Stéphan Tulkens <stephantul@gmail.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2024 The Minish Lab
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/MinishLab
|
|
29
|
+
Project-URL: Bug Reports, https://github.com/MinishLab/semhash/issues
|
|
30
|
+
Project-URL: Source, https://github.com/MinishLab/semhash
|
|
31
|
+
Classifier: Development Status :: 4 - Beta
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: Intended Audience :: Science/Research
|
|
34
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
35
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
36
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
37
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
42
|
+
Classifier: Natural Language :: English
|
|
43
|
+
Requires-Python: >=3.9
|
|
44
|
+
Description-Content-Type: text/markdown
|
|
45
|
+
License-File: LICENSE
|
|
46
|
+
Requires-Dist: model2vec>=0.3.0
|
|
47
|
+
Requires-Dist: vicinity[usearch]>=0.3.4
|
|
48
|
+
Provides-Extra: dev
|
|
49
|
+
Requires-Dist: black; extra == "dev"
|
|
50
|
+
Requires-Dist: ipython; extra == "dev"
|
|
51
|
+
Requires-Dist: mypy; extra == "dev"
|
|
52
|
+
Requires-Dist: pre-commit; extra == "dev"
|
|
53
|
+
Requires-Dist: pytest; extra == "dev"
|
|
54
|
+
Requires-Dist: pytest-coverage; extra == "dev"
|
|
55
|
+
Requires-Dist: ruff; extra == "dev"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
<div align="center">
|
|
59
|
+
|
|
60
|
+
# SemHash: Fast Semantic Text Deduplication
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
[Quickstart](#quickstart) •
|
|
64
|
+
[Main Features](#main-features) •
|
|
65
|
+
[Usage](#usage)
|
|
66
|
+
[Benchmarks](#benchmarks)
|
|
67
|
+
|
|
68
|
+
</div>
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
SemHash is a technique to efficiently deduplicate datasets based on semantic similarity. It uses a combination of lightning-fast embeddings through [model2vec](https://github.com/MinishLab/model2vec) and ANN-based similarity search through [vicinity](https://github.com/MinishLab/vicinity).
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
## Quickstart
|
|
76
|
+
|
|
77
|
+
Install the package with:
|
|
78
|
+
```bash
|
|
79
|
+
pip install semhash
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Deduplicate a single dataset with the following code:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from model2vec import StaticModel
|
|
86
|
+
from semhash import SemHash
|
|
87
|
+
|
|
88
|
+
# Load an embedding model
|
|
89
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
|
|
90
|
+
|
|
91
|
+
# Initialize a SemHash with the model
|
|
92
|
+
semhash = SemHash(model=model)
|
|
93
|
+
|
|
94
|
+
# Create some texts to deduplicate
|
|
95
|
+
texts = [
|
|
96
|
+
"It's dangerous to go alone!",
|
|
97
|
+
"It's dangerous to go alone!", # Exact duplicate
|
|
98
|
+
"It's not safe to go by yourself!", # Semantically similar
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
# Deduplicate the texts
|
|
102
|
+
deduplicated_texts = semhash.fit_deduplicate(records=texts, threshold=0.5)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
For more advanced usage, you can also deduplicate across multiple datasets, or deduplicate multi-column datasets. Examples are provided in the [usage](#usage) section.
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
## Main Features
|
|
109
|
+
|
|
110
|
+
- **Fast**: SemHash uses model2vec to embed texts and vicinity to perform similarity search, making it extremely fast.
|
|
111
|
+
- **Scalable**: SemHash can deduplicate large datasets with millions of records thanks to the ANN backends in Vicinity.
|
|
112
|
+
- **Flexible**: SemHash can be used to deduplicate a single dataset or across two datasets, and can also be used to deduplicate multi-column datasets (such as QA datasets).
|
|
113
|
+
- **Lightweight**: SemHash is a lightweight package with minimal dependencies, making it easy to install and use.
|
|
114
|
+
|
|
115
|
+
## Usage
|
|
116
|
+
|
|
117
|
+
<details>
|
|
118
|
+
<summary> Deduplicate a single dataset </summary>
|
|
119
|
+
<br>
|
|
120
|
+
|
|
121
|
+
The following code snippet shows how to deduplicate a single dataset using SemHash:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from model2vec import StaticModel
|
|
125
|
+
from semhash import SemHash
|
|
126
|
+
|
|
127
|
+
# Load an embedding model
|
|
128
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
|
|
129
|
+
|
|
130
|
+
# Initialize a SemHash with the model
|
|
131
|
+
semhash = SemHash(model=model)
|
|
132
|
+
|
|
133
|
+
# Create some texts to deduplicate
|
|
134
|
+
texts = [
|
|
135
|
+
"It's dangerous to go alone!",
|
|
136
|
+
"It's dangerous to go alone!", # Exact duplicate
|
|
137
|
+
"It's not safe to go by yourself!", # Semantically similar
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
# Deduplicate the texts
|
|
141
|
+
deduplicated_texts = semhash.fit_deduplicate(records=texts, threshold=0.5)
|
|
142
|
+
```
|
|
143
|
+
</details>
|
|
144
|
+
|
|
145
|
+
<details>
|
|
146
|
+
<summary> Deduplicate across two datasets </summary>
|
|
147
|
+
<br>
|
|
148
|
+
|
|
149
|
+
The following code snippet shows how to deduplicate across two datasets using SemHash (in this example, a training and test dataset):
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
from model2vec import StaticModel
|
|
153
|
+
from semhash import SemHash
|
|
154
|
+
|
|
155
|
+
# Load an embedding model
|
|
156
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
|
|
157
|
+
|
|
158
|
+
# Initialize a SemHash with the model
|
|
159
|
+
semhash = SemHash(model=model)
|
|
160
|
+
|
|
161
|
+
# Create some texts to deduplicate
|
|
162
|
+
train = [
|
|
163
|
+
"It's dangerous to go alone!",
|
|
164
|
+
"It's a secret to everybody.",
|
|
165
|
+
"Ganondorf has invaded Hyrule!",
|
|
166
|
+
]
|
|
167
|
+
test = [
|
|
168
|
+
"It's dangerous to go alone!", # Exact duplicate
|
|
169
|
+
"It's not safe to go by yourself!", # Semantically similar
|
|
170
|
+
"The master sword seals the darkness",
|
|
171
|
+
]
|
|
172
|
+
|
|
173
|
+
# Fit on the training data
|
|
174
|
+
semhash.fit(records=train)
|
|
175
|
+
# Deduplicate the test data against the training data
|
|
176
|
+
deduplicated_texts = semhash.deduplicate(records=test, threshold=0.5)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
</details>
|
|
180
|
+
|
|
181
|
+
<details>
|
|
182
|
+
<summary> Deduplicate multi-column datasets </summary>
|
|
183
|
+
<br>
|
|
184
|
+
|
|
185
|
+
The following code snippet shows how to deduplicate multi-column datasets using SemHash (in this example, a QA dataset with questions, contexts, and answers):
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
from model2vec import StaticModel
|
|
189
|
+
from semhash import SemHash
|
|
190
|
+
|
|
191
|
+
# Load an embedding model
|
|
192
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
|
|
193
|
+
|
|
194
|
+
# Initialize a SemHash with the model and columns to deduplicate
|
|
195
|
+
semhash = SemHash(model=model, columns=["question", "context", "answer"])
|
|
196
|
+
|
|
197
|
+
# Create some texts to deduplicate
|
|
198
|
+
records = [
|
|
199
|
+
{"question": "What is the hero's name?", "context": "The hero is Link", "answer": "Link"},
|
|
200
|
+
{"question": "What is the hero's name?", "context": "The hero is Link", "answer": "Link"}, # Exact duplicate
|
|
201
|
+
{
|
|
202
|
+
"question": "Who is the protagonist?",
|
|
203
|
+
"context": "In this story, Link is the hero",
|
|
204
|
+
"answer": "Link",
|
|
205
|
+
}, # Semantically similar
|
|
206
|
+
{"question": "Who is the princess?", "context": "The princess is Zelda", "answer": "Zelda"},
|
|
207
|
+
]
|
|
208
|
+
|
|
209
|
+
# Deduplicate the records
|
|
210
|
+
deduplicated_records = semhash.fit_deduplicate(records=records, threshold=0.5)
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
</details>
|
|
214
|
+
|
|
215
|
+
## Benchmarks
|
|
216
|
+
|
|
217
|
+
We've benchmarked SemHash on a variety of datasets to measure the deduplication performance and speed. The benchmarks were run with the following setup:
|
|
218
|
+
- The benchmarks were all run on CPU
|
|
219
|
+
- The benchmarks were all run with `ann=True`
|
|
220
|
+
- The timings include the encoding time, index building time, and deduplication time.
|
|
221
|
+
|
|
222
|
+
### Train Deduplication Benchmark
|
|
223
|
+
|
|
224
|
+
| Dataset | Original Train Size | Deduplicated Train Size | % Removed | Deduplication Time (s) |
|
|
225
|
+
| --- | --- | --- | --- | --- |
|
|
226
|
+
| bbc | 1225 | 1144 | 6.61 | 0.23 |
|
|
227
|
+
| senteval_cr | 3012 | 2990 | 0.73 | 0.13 |
|
|
228
|
+
| tweet_sentiment_extraction | 27481 | 26695 | 2.86 | 1.64 |
|
|
229
|
+
| emotion | 16000 | 15696 | 1.90 | 0.66 |
|
|
230
|
+
| amazon_counterfactual | 5000 | 4992 | 0.16 | 0.31 |
|
|
231
|
+
| ag_news | 120000 | 106921 | 10.90 | 4.21 |
|
|
232
|
+
| enron_spam | 31716 | 20539 | 35.24 | 1.57 |
|
|
233
|
+
| subj | 8000 | 7990 | 0.12 | 0.57 |
|
|
234
|
+
| sst5 | 8544 | 8526 | 0.21 | 0.55 |
|
|
235
|
+
| 20_newgroups | 11314 | 10685 | 5.56 | 0.69 |
|
|
236
|
+
| hatespeech_offensive | 22783 | 22090 | 3.04 | 0.84 |
|
|
237
|
+
| ade | 17637 | 15718 | 10.88 | 0.68 |
|
|
238
|
+
| imdb | 25000 | 24832 | 0.67 | 1.65 |
|
|
239
|
+
| massive_scenario | 11514 | 9366 | 18.66 | 0.43 |
|
|
240
|
+
| student | 117519 | 63865 | 45.66 | 4.18 |
|
|
241
|
+
| squad_v2 | 130319 | 115546 | 11.34 | 11.20 |
|
|
242
|
+
| wikitext | 1801350 | 884586 | 50.89 | 56.11 |
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
### Train/Test Deduplication Benchmark
|
|
246
|
+
|
|
247
|
+
| Dataset | Train Size | Test Size | Deduplicated Test Size | % Removed | Deduplication Time (s) |
|
|
248
|
+
| --- | --- | --- | --- | --- | --- |
|
|
249
|
+
| bbc | 1225 | 1000 | 875 | 12.50 | 0.39 |
|
|
250
|
+
| senteval_cr | 3012 | 753 | 750 | 0.40 | 0.11 |
|
|
251
|
+
| tweet_sentiment_extraction | 27481 | 3534 | 3411 | 3.48 | 0.86 |
|
|
252
|
+
| emotion | 16000 | 2000 | 1926 | 3.70 | 0.56 |
|
|
253
|
+
| amazon_counterfactual | 5000 | 5000 | 4990 | 0.20 | 0.48 |
|
|
254
|
+
| ag_news | 120000 | 7600 | 6197 | 18.46 | 3.38 |
|
|
255
|
+
| enron_spam | 31716 | 2000 | 1063 | 46.85 | 1.98 |
|
|
256
|
+
| subj | 8000 | 2000 | 1999 | 0.05 | 0.58 |
|
|
257
|
+
| sst5 | 8544 | 2210 | 2205 | 0.23 | 0.56 |
|
|
258
|
+
| 20_newgroups | 11314 | 7532 | 7310 | 2.95 | 2.26 |
|
|
259
|
+
| hatespeech_offensive | 22783 | 2000 | 1926 | 3.70 | 0.72 |
|
|
260
|
+
| ade | 17637 | 5879 | 4954 | 15.73 | 0.82 |
|
|
261
|
+
| imdb | 25000 | 25000 | 24805 | 0.78 | 2.65 |
|
|
262
|
+
| massive_scenario | 11514 | 2974 | 2188 | 26.43 | 0.43 |
|
|
263
|
+
| student | 117519 | 5000 | 2395 | 52.10 | 3.02 |
|
|
264
|
+
| squad_v2 | 130319 | 11873 | 11869 | 0.03 | 9.11 |
|
|
265
|
+
| wikitext | 1801350 | 4358 | 3610 | 17.16 | 36.10 |
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
As can be seen, SemHash is extremely fast, and scales to large datasets with millions of records. There are some notable examples of train/test leakage, such as `enron_spam` and `student`, where the test dataset contains a significant amount of semantic overlap with the training dataset.
|
|
269
|
+
|
|
270
|
+
### Reproducing the Benchmarks
|
|
271
|
+
|
|
272
|
+
To run the benchmarks yourself, you can use the following command:
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
python -m benchmarks.run_benchmarks
|
|
276
|
+
```
|
|
277
|
+
Optionally, the datasets can be updated in the [datasets.py](https://github.com/MinishLab/semhash/blob/main/benchmarks/datasets.py) file.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
semhash/__init__.py,sha256=5JouP1_xDkl0wS-OZjsCTrWRVZUZEWGWDHnIZqV7wso,59
|
|
2
|
+
semhash/semhash.py,sha256=z5QFVlrfSKvw7SlNg6E1MjCcBrRhvRiXGYYR_AZr61w,7445
|
|
3
|
+
semhash/utils.py,sha256=AtoRoR7_zFNO-_x623zBIYlkP86GJFapPQaigVh6IRE,511
|
|
4
|
+
semhash/version.py,sha256=0ZST8YQ_2d0ualYw52Frv3F_O9ULTFPCjDUI8Zy4qoA,84
|
|
5
|
+
semhash-0.1.0.dist-info/LICENSE,sha256=6CbsCtUBhLgsb6-YTEeH38lhp-qr9KhOAWOYT0sz_58,1071
|
|
6
|
+
semhash-0.1.0.dist-info/METADATA,sha256=_RTy0cN63RKA0W4Tz8bwDuXWn0cakTPlAPXw375jc5o,10328
|
|
7
|
+
semhash-0.1.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
|
|
8
|
+
semhash-0.1.0.dist-info/top_level.txt,sha256=vHyg0MJJmAg1KqrrVHOFN2Rt7saCWXiACTIE2lN3htY,8
|
|
9
|
+
semhash-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
semhash
|