当前位置:   article > 正文

prompt 代码示例_prompt模板示例:

prompt模板示例:

1. 定义任务

from openprompt.data_utils import InputExample
classes=[
    'negative',
    'positive'
]

dataset=[
    InputExample(
        guid = 0,
        text_a = "Albert Einstein was one of the greatest intellects of his time.",
    ),
    InputExample(
        guid = 1,
        text_a = "The film was badly made.",
    ),
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

2. 定义预训练语言模型

from openprompt.plms import load_plm
plm,tokenizer,model_config,WrapperClass=load_plm('bert',"bert-base-cased")
  • 1
  • 2

3. 定义prompt模板

from openprompt.prompts import ManualTemplate
promptTemplate=ManualTemplate(
    text='{"placeholder":"text_a"} It was {"mask"}',
    tokenizer=tokenizer,
)
  • 1
  • 2
  • 3
  • 4
  • 5

4. 定义输出-label映射

from openprompt.prompts import ManualVerbalizer
promptVerbalizer=ManualVerbalizer(
    classes=classes,
    label_words={
        'negative':['bad'],
        'positive':['good','wonderful','great'],
    },
    tokenizer=tokenizer,
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5. 组合构建为PromptModel类

from openprompt import PromptForClassification
promptModel=PromptForClassification(
    template=promptTemplate,
    plm=plm,
    verbalizer=promptVerbalizer,
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

6. 定义dataloader

from openprompt import PromptDataLoader
data_loader=PromptDataLoader(
    dataset=dataset,
    tokenizer=tokenizer,
    template=promptTemplate,
    tokenizer_wrapper_class=WrapperClass,
)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

7. 开始训练、测试

# making zero-shot inference using pretrained MLM with prompt
promptModel.eval()
with torch.no_grad():
    for batch in data_loader:
        logits=promptModel(batch)
        preds=torch.argmax(logits,dim=-1)
        print(classes[preds])
        # predictions would be 1, 0 for classes 'positive', 'negative'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

参考知乎

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/376733?site
推荐阅读
相关标签
  

闽ICP备14008679号