跳到内容

MinHashDedup

使用 MinHashMinHashLSH 去重文本。

MinHashDedup 是一个 Step,用于检测数据集中的近似重复项。其思路大致可转化为以下步骤:1. 将文本分词为单词或 n-gram。2. 为每个文本创建一个 MinHash。3. 将 MinHash 存储在 MinHashLSH 中。4. 检查 MinHash 是否已在 LSH 中,如果在,则为重复项。

属性

  • num_perm:要使用的排列数。默认为 128

  • seed:用于 MinHash 的种子。默认为 1

  • tokenizer:要使用的分词器。可用的有 wordsngrams。如果选择 words,它将使用 nltk 的单词分词器将文本分词为单词。ngram 估计 n-gram(以及大小 n)。默认为 words

  • n:要使用的 n-gram 的大小。仅在 tokenizer="ngrams" 时相关。默认为 5

  • threshold:将两个 MinHash 视为重复项的阈值。值越接近 0,检测到的重复项越多。默认为 0.9

  • storage:用于 LSH 的存储。可以是 dict 以将索引存储在内存中,也可以是 disk。请注意,disk 是一个实验性功能,未在 datasketch 中定义,它基于 DiskCache 的 Index 类。它应该像 dict 一样工作,但由磁盘支持,但根据系统,它可能会较慢。默认为 dict

输入和输出列

graph TD
    subgraph Dataset
        subgraph Columns
            ICOL0[text]
        end
        subgraph New columns
            OCOL0[keep_row_after_minhash_filtering]
        end
    end

    subgraph MinHashDedup
        StepInput[Input Columns: text]
        StepOutput[Output Columns: keep_row_after_minhash_filtering]
    end

    ICOL0 --> StepInput
    StepOutput --> OCOL0
    StepInput --> StepOutput

输入

  • text (str):要过滤的文本。

输出

  • keep_row_after_minhash_filtering (bool):布尔值,指示 piece text 是否不是重复项,即应保留此文本。

示例

使用 MinHash 和 MinHashLSH 去重文本列表

from distilabel.pipeline import Pipeline
from distilabel.steps import MinHashDedup
from distilabel.steps import LoadDataFromDicts

with Pipeline() as pipeline:
    ds_size = 1000
    batch_size = 500  # Bigger batch sizes work better for this step
    data = LoadDataFromDicts(
        data=[
            {"text": "This is a test document."},
            {"text": "This document is a test."},
            {"text": "Test document for duplication."},
            {"text": "Document for duplication test."},
            {"text": "This is another unique document."},
        ]
        * (ds_size // 5),
        batch_size=batch_size,
    )
    minhash_dedup = MinHashDedup(
        tokenizer="words",
        threshold=0.9,      # lower values will increase the number of duplicates
        storage="dict",     # or "disk" for bigger datasets
    )

    data >> minhash_dedup

if __name__ == "__main__":
    distiset = pipeline.run(use_cache=False)
    ds = distiset["default"]["train"]
    # Filter out the duplicates
    ds_dedup = ds.filter(lambda x: x["keep_row_after_minhash_filtering"])

参考