huggingface重新加载后如何使用fine-tuned模型进行实际预测?

问题描述 投票:0回答:1

我正在尝试重新加载我已经微调的 DistilBertForSequenceClassification 模型,并使用它来将一些句子预测到它们适当的标签中(文本分类)。

在google Colab中,成功训练BERT模型后,保存后下载:

trainer.train()
trainer.save_model("distilbert_classification")

下载的模型有三个文件:config.json、pytorch_model.bin、training_args.bin。

我将它们移动到我的谷歌驱动器中某个名为“distilbert_classification”的文件夹中。

之后,我将模型重新加载到不同的 Colab 笔记本中:


reloadtrainer = DistilBertForSequenceClassification.from_pretrained('google drive directory/distilbert_classification')

到目前为止,我已经成功了,没有任何错误。

但是,如何使用这个重新加载的模型(“reloadtrainer”对象)来实际对句子进行预测?之后我需要使用的代码是什么?我试过了

reloadtrainer .predict("sample sentence")
但它不起作用。将不胜感激任何帮助!

python deep-learning huggingface-transformers text-classification huggingface
1个回答
1
投票

请记住,您还需要对模型的输入进行标记化,就像在训练阶段一样。仅仅向模型输入一个句子是行不通的(除非你使用

pipelines()
但那是另一个讨论)。

您可以使用

AutoModelForSequenceClassification()
AutoTokenizer()
使事情变得更容易。

请注意,我保存模型的方式是通过

model.save_pretrained("path_to_model")
而不是
model.save()
.

一种可能的方法如下(假设您使用 uncased distilbert 进行训练):

  model = AutoModelForSequenceClassification.from_pretrained("path_to_model")
  # Replace with whatever tokenizer you used
  tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased", use_fast=True)
  input_text = "This is the text I am trying to classify."
  tokenized_text = tokenizer(input_text,
                             truncation=True,
                             is_split_into_words=False,
                             return_tensors='pt')
  outputs = model(tokenized_text["input_ids"])
  predicted_label = outputs.logits.argmax(-1)
© www.soinside.com 2019 - 2024. All rights reserved.