【问题标题】:How to use fine-tuned model in huggingface for actual prediction after re-loading?重新加载后如何在拥抱脸中使用微调模型进行实际预测?
【发布时间】:2022-08-20 16:34:24
【问题描述】:

我正在尝试重新加载一个经过微调的 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


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 2021-08-08
      • 2021-05-14
      • 2021-11-21
      • 2022-01-17
      • 2021-01-15
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多