使用huggingface transformers进行多次训练,除了第一次之外,结果将完全相同

我有一个函数,它会从huggingface加载预训练模型,并对其进行微调以进行情感分析,然后计算F1分数并返回结果。问题是当我多次调用这个函数并使用完全相同的参数时,它会返回完全相同的指标分数,这是预期的,除了第一次结果不同,这是怎么回事?

这是我的函数,基于huggingface的这个教程编写的:

import uuidimport numpy as npfrom datasets import (    load_dataset,    load_metric,    DatasetDict,    concatenate_datasets)from transformers import (    AutoTokenizer,    AutoModelForSequenceClassification,    DataCollatorWithPadding,    TrainingArguments,    Trainer,)CHECKPOINT = "distilbert-base-uncased"SAVING_FOLDER = "sst2"def custom_train(datasets, checkpoint=CHECKPOINT, saving_folder=SAVING_FOLDER):    model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)    tokenizer = AutoTokenizer.from_pretrained(checkpoint)        def tokenize_function(example):        return tokenizer(example["sentence"], truncation=True)    tokenized_datasets = datasets.map(tokenize_function, batched=True)    data_collator = DataCollatorWithPadding(tokenizer=tokenizer)    saving_folder = f"{SAVING_FOLDER}_{str(uuid.uuid1())}"    training_args = TrainingArguments(saving_folder)    trainer = Trainer(        model,        training_args,        train_dataset=tokenized_datasets["train"],        eval_dataset=tokenized_datasets["validation"],        data_collator=data_collator,        tokenizer=tokenizer,    )        trainer.train()        predictions = trainer.predict(tokenized_datasets["test"])    print(predictions.predictions.shape, predictions.label_ids.shape)    preds = np.argmax(predictions.predictions, axis=-1)        metric_fun = load_metric("f1")    metric_result = metric_fun.compute(predictions=preds, references=predictions.label_ids)        return metric_result

然后我会用相同的数据集多次运行这个函数,并每次附加返回的F1分数结果:

raw_datasets = load_dataset("glue", "sst2")small_datasets = DatasetDict({    "train": raw_datasets["train"].select(range(100)).flatten_indices(),    "validation": raw_datasets["validation"].select(range(100)).flatten_indices(),    "test": raw_datasets["validation"].select(range(100, 200)).flatten_indices(),})results = []for i in range(4):    result = custom_train(small_datasets)    results.append(result)

然后当我检查结果列表时:

[{'f1': 0.7755102040816325}, {'f1': 0.5797101449275361}, {'f1': 0.5797101449275361}, {'f1': 0.5797101449275361}]

可能想到的是,当我加载预训练模型时,头部会被随机权重初始化,这就是结果不同的原因,如果是这样,为什么只有第一次不同,而其他结果完全相同?


回答:

Sylvain Gugger 在这里回答了这个问题: https://discuss.huggingface.co/t/multiple-training-will-give-exactly-the-same-result-except-for-the-first-time/8493

您需要在实例化模型之前设置种子,否则随机头部不会以相同的方式初始化,这就是为什么第一次运行总是不同的。后续的运行都相同,因为种子已在训练方法中由Trainer设置。要设置种子:

from transformers import set_seedset_seed(42)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注