bert模型部署 bert_base 和 bert_serving

部署需要把模型压缩成pb文件,但是需要一些前期准备

首先需要生成label2id.pkl 这个文件,需要添加代码在run_classifier.py或自己的运行任务文件中

    #---------
    import pickle
    output_label2id_file = os.path.join(FLAGS.output_dir, "label2id.pkl")
    if not os.path.exists(output_label2id_file):
        with open(output_label2id_file, 'wb') as w:
            pickle.dump(label_map, w)
    #---------

 

def convert_single_example(ex_index, example, label_list, max_seq_length,
                           tokenizer):
    """Converts a single `InputExample` into a single `InputFeatures`."""

    if isinstance(example, PaddingInputExample):
        return InputFeatures(
            input_ids=[0] * max_seq_length,
            input_mask=[0] * max_seq_length,
            segment_ids=[0] * max_seq_length,
            label_id=0,
            is_real_example=False)

    label_map = {}
    for (i, label) in enumerate(label_list):
        label_map[label] = i
   
    #---------
    import pickle
    output_label2id_file = os.path.join(FLAGS.output_dir, "label2id.pkl")
    if not os.path.exists(output_label2id_file):
        with open(output_label2id_file, 'wb') as w:
            pickle.dump(label_map, w)
    #---------

    tokens_a = tokenizer.tokenize(example.text_a)
    tokens_b = None
    if example.text_b:
        tokens_b = tokenizer.tokenize(example.text_b)

    if tokens_b:
        # Modifies `tokens_a` and `tokens_b` in place so that the total
        # length is less than the specified length.
        # Account for [CLS], [SEP], [SEP] with "- 3"
        _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
    else:
        # Account for [CLS] and [SEP] with "- 2"
        if len(tokens_a) > max_seq_length - 2:
            tokens_a = tokens_a[0:(max_seq_length - 2)]

 

然后需要创建 freeze_graph.py 这个文件(代码放在最后)

然后运行 freeze_graph.py

bert_model_dir 是训练完模型的路径

model_dir 是输出pb模型的路径

注意参数和之前统一

然后会看到生成了 .pd  文件

有的时候报错是因为需要 bert_config.json 和 vocab 两个文件,这个在下载的BERT模型文件夹里面可以找到

例 chinese_L-12_H-768_A-12 里面就有,BERT官方链接 https://github.com/google-research/bert/

python free
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值