90. 归一化后去除重复训练文本
重复的样本会在训练集和测试集之间造成数据泄露,导致模型产生记忆。精确匹配会漏掉仅在大小写或空格上有所不同的副本。
编写 dedupe_texts(texts)。通过转换为小写、去除首尾空格以及将连续的空格合并为一个空格来归一化每段文本。保留每个归一化文本的首次出现,并按顺序返回保留文本的索引。
def dedupe_texts(texts)示例 1
输入: dedupe_texts(["Hi there", "hi there", "Bye"])
输出: [0, 2]
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Two texts are duplicates when their normalised forms match, so build a normalised key and remember which keys you have already seen.
提示 2
Loop over texts with their index, normalise each one, and if the key is not in a seen set, add it and record the index.
提示 3
' '.join(t.lower().split()) lowercases, strips, and collapses every whitespace run in one step; keep indices in a list so the original order is preserved.
理解思路
重复的训练样本会让模型产生记忆,并可能在训练集和测试集之间造成泄露。精确的字符串匹配会漏掉仅在大小写或空格上有所不同的副本,因此首先要归一化每段文本,然后仅保留每个归一化形式首次出现的位置。使用一个已见过的 key 集合(set)可以实现快速的一次遍历。
texts [' Hello World', 'hello world ', 'HELLO\tworld', 'bye']。转换为小写、去除首尾空格并将所有连续的空白符(空格、制表符、换行符)转换为单个空格后,前三个文本都变为 'hello world',最后一个为 'bye'。保留索引 0,跳过 1 和 2,保留 3。答案为 [0, 3]。
key = lowercase, strip, 然后将连续的空格合并为一个空格;如果 key 是新的,记录索引并将 key 添加到集合中;按顺序返回保留的索引。仅使用小写化处理会将不同的空格间距视为不同的文本。实际的流水线会进一步进行近重复检测(near-duplicate detection),但这种精确的归一化匹配是清洗预训练和微调数据集的低成本第一步。