构造方法
DataCollatorForTokenClassification( 
	tokenizer: PreTrainedTokenizerBase,
	padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = True,
	max_length: typing.Optional[int] = None,
	pad_to_multiple_of: typing.Optional[int] = None,
	label_pad_token_id: int = -100,
	return_tensors: str = 'pt' 
	)

在进行NER(实体命名识别)任务时使用的数据收集器,该数据收集器不仅会动态的处理输入的数据,而且会处理数据的标签。

参数tokenizer表示用于编码数据的分词器。

参数padding表示填充方式,可以为布尔类型、字符串类型或者一个PaddingStrategy对象。当值为布尔类型时,True表示填充至最大序列长度,False表示不填充。当为字符串类型时,"longest"表示填充值最大序列长度,"max_length"表示填充值参数max_length设置的长度,"do_not_pad"表示不填充。

参数max_length表示填充序列的最大长度,当设置padding="max_length"时,该参数才会有用。

参数pad_to_multiple_of表示填充的序列的倍数。

参数label_pad_token_id表示填充标签时的值,默认为-100。注意,默认数据中序列填充的值为0,这与标签填充的值不一致。

参数return_tensors表示返回数据的类型,有三个可选项,分别是"tf"、“pt”、“np”,分别表示tensorflow可以处理的数据类型,pytorch可以处理的数据类型以及numpy数据类型。

使用示例
def preprocess_fn(data):
    tokenized_inputs = tokenizer(data["tokens"], truncation=True, is_split_into_words=True)
    labels = []
    for i, label in enumerate(data["ner_tags"]):
        word_ids = tokenized_inputs.word_ids(batch_index=i)
        previous_word_id = None
        label_ids = []
        for idx in word_ids:
            if idx is None:
                label_ids.append(-100)
            elif idx != previous_word_id:
                label_ids.append(label[idx])
            previous_word_id = idx
        labels.append(label_ids)
    tokenized_inputs["labels"] = labels
    return tokenized_inputs

dataset = datasets.load_dataset("conll2003")
label_list = dataset["train"].features["ner_tags"].feature.names
tokenizer = transformers.AutoTokenizer.from_pretrained("distilbert-base-uncased")
data_collator = transformers.DataCollatorForTokenClassification(tokenizer=tokenizer,
                                                                padding=True,
                                                                label_pad_token_id=-100,
                                                                return_tensors="tf")
dataset = dataset.map(preprocess_fn,
                      batched=True,
                      batch_size=1000,
                      remove_columns=["id", "tokens", "pos_tags", "chunk_tags", "ner_tags"])
train_dataset = dataset["train"].to_tf_dataset(columns=["input_ids", "attention_mask"],
                                               batch_size=16,
                                               shuffle=True,
                                               collate_fn=data_collator,
                                               label_cols=["labels"])

GitHub 加速计划 / tra / transformers
130.24 K
25.88 K
下载
huggingface/transformers: 是一个基于 Python 的自然语言处理库,它使用了 PostgreSQL 数据库存储数据。适合用于自然语言处理任务的开发和实现,特别是对于需要使用 Python 和 PostgreSQL 数据库的场景。特点是自然语言处理库、Python、PostgreSQL 数据库。
最近提交(Master分支:2 个月前 )
33868a05 * [i18n-HI] Translated accelerate page to Hindi * Update docs/source/hi/accelerate.md Co-authored-by: K.B.Dharun Krishna <kbdharunkrishna@gmail.com> * Update docs/source/hi/accelerate.md Co-authored-by: K.B.Dharun Krishna <kbdharunkrishna@gmail.com> * Update docs/source/hi/accelerate.md Co-authored-by: K.B.Dharun Krishna <kbdharunkrishna@gmail.com> * Update docs/source/hi/accelerate.md Co-authored-by: K.B.Dharun Krishna <kbdharunkrishna@gmail.com> --------- Co-authored-by: Kay <kay@Kays-MacBook-Pro.local> Co-authored-by: K.B.Dharun Krishna <kbdharunkrishna@gmail.com> 13 天前
e2ac16b2 * rework converter * Update modular_model_converter.py * Update modular_model_converter.py * Update modular_model_converter.py * Update modular_model_converter.py * cleaning * cleaning * finalize imports * imports * Update modular_model_converter.py * Better renaming to avoid visiting same file multiple times * start converting files * style * address most comments * style * remove unused stuff in get_needed_imports * style * move class dependency functions outside class * Move main functions outside class * style * Update modular_model_converter.py * rename func * add augmented dependencies * Update modular_model_converter.py * Add types_to_file_type + tweak annotation handling * Allow assignment dependency mapping + fix regex * style + update modular examples * fix modular_roberta example (wrong redefinition of __init__) * slightly correct order in which dependencies will appear * style * review comments * Performance + better handling of dependencies when they are imported * style * Add advanced new classes capabilities * style * add forgotten check * Update modeling_llava_next_video.py * Add prority list ordering in check_conversion as well * Update check_modular_conversion.py * Update configuration_gemma.py 13 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐