当前位置: 首页 > news >正文

专门做旅游的网站网站推广的内容

专门做旅游的网站,网站推广的内容,博彩网站被劫持,网站模板 带数据库在深度学习中,将模型导出为ONNX(Open Neural Network Exchange)格式并利用ONNX进行推理是提高推理速度和模型兼容性的一种常见做法。本文将介绍如何将BERT句子模型导出为ONNX格式,并使用ONNX Runtime进行推理,具体以中…

在深度学习中,将模型导出为ONNX(Open Neural Network Exchange)格式并利用ONNX进行推理是提高推理速度和模型兼容性的一种常见做法。本文将介绍如何将BERT句子模型导出为ONNX格式,并使用ONNX Runtime进行推理,具体以中文文本处理为例。

1. 什么是ONNX?

ONNX 是一种开放的神经网络交换格式,旨在促进深度学习模型在不同平台和工具之间的共享和移植。它支持包括PyTorch、TensorFlow等多种主流框架,可以通过ONNX Runtime库高效推理。通过将模型转换为ONNX格式,我们可以获得跨平台部署的优势,并利用ONNX Runtime加速推理过程。

2. 准备工作

在导出和推理之前,需要安装以下库:

pip install torch transformers onnx onnxruntime

3. 导出BERT句子模型为ONNX

首先,我们将使用HuggingFace的transformers库加载一个预训练的BERT句子模型(text2vec-base-chinese),然后将其导出为ONNX格式。以下是导出模型的步骤和代码:

3.1 导出模型的代码

import torch
from transformers import BertTokenizer, BertModel# 加载预训练的BERT模型和分词器
tokenizer = BertTokenizer.from_pretrained('shibing624/text2vec-base-chinese')
model = BertModel.from_pretrained('shibing624/text2vec-base-chinese')# 读取要处理的句子
with open("corpus/words_nlu.txt", 'rt', encoding='utf-8') as f:nlu_words = [line.strip() for line in f.readlines()]
nlu_words.insert(0, "摄像头打开一下")  # 插入要比较的句子# 对句子进行编码
encoded_input = tokenizer(nlu_words, padding=True, truncation=True, return_tensors='pt')# 设置ONNX模型的保存路径
onnx_model_path = "text2vec-base-chinese.onnx"
model.eval()# 导出模型为ONNX格式
with torch.no_grad():torch.onnx.export(model,(encoded_input['input_ids'], encoded_input['attention_mask']),onnx_model_path,input_names=['input_ids', 'attention_mask'],output_names=['last_hidden_state'],opset_version=14,dynamic_axes={'input_ids': {0: 'batch_size', 1: 'sequence_length'},'attention_mask': {0: 'batch_size', 1: 'sequence_length'},'last_hidden_state': {0: 'batch_size', 1: 'sequence_length'}})
print(f"ONNX模型已导出到 {onnx_model_path}")

在这段代码中,我们将text2vec-base-chinese模型导出为ONNX格式,指定了输入和输出的名称,并使用了动态轴设置(如批大小和序列长度),这样可以处理不同长度的句子。

4. 使用ONNX进行推理

导出模型后,我们可以使用ONNX Runtime进行推理。以下是基于ONNX的推理代码。该代码实现了对输入文本进行预处理、调用ONNX模型进行推理、以及对模型输出进行均值池化处理。

4.1 ONNX推理代码

import numpy as np
from onnxruntime import InferenceSessionclass PIPE_NLU:def __init__(self, model_path="text2vec-base-chinese.onnx", vocab_path="vocab.txt") -> None:self.model_path = model_pathself.vocab_path = vocab_pathself.vocab = self.load_vocab(vocab_path)self.onnx_session = InferenceSession(model_path)print("成功加载NLU解码器")def load_vocab(self, vocab_path):"""加载BERT词汇表"""vocab = {}with open(vocab_path, 'r', encoding='utf-8') as f:for idx, line in enumerate(f):token = line.strip()vocab[token] = idxreturn vocabdef tokenize(self, text):"""将文本分词为BERT的input_ids"""tokens = ['[CLS]']for char in text:if char in self.vocab:tokens.append(char)else:tokens.append('[UNK]')tokens.append('[SEP]')input_ids = [self.vocab[token] if token in self.vocab else self.vocab['[UNK]'] for token in tokens]return input_idsdef preprocess(self, texts, max_length=128):"""对输入文本进行预处理"""input_ids_list = []attention_mask_list = []for text in texts:input_ids = self.tokenize(text)if len(input_ids) > max_length:input_ids = input_ids[:max_length]else:input_ids += [0] * (max_length - len(input_ids))attention_mask = [1 if idx != 0 else 0 for idx in input_ids]input_ids_list.append(input_ids)attention_mask_list.append(attention_mask)inputs = {'input_ids': np.array(input_ids_list, dtype=np.int64),'attention_mask': np.array(attention_mask_list, dtype=np.int64)}return inputsdef mean_pooling_numpy(self, model_output, attention_mask):"""对模型输出进行均值池化"""token_embeddings = model_outputinput_mask_expanded = np.expand_dims(attention_mask, -1).astype(float)return np.sum(token_embeddings * input_mask_expanded, axis=1) / np.clip(np.sum(input_mask_expanded, axis=1), a_min=1e-9, a_max=None)def compute_embeddings(self, texts):"""计算输入文本的句子嵌入"""onnx_inputs = self.preprocess(texts)onnx_outputs = self.onnx_session.run(None, onnx_inputs)last_hidden_state = onnx_outputs[0]sentence_embeddings = self.mean_pooling_numpy(last_hidden_state, onnx_inputs['attention_mask'])sentence_embeddings = sentence_embeddings / np.linalg.norm(sentence_embeddings, axis=1, keepdims=True)return sentence_embeddings

4.2 推理流程

  1. 加载ONNX模型:通过InferenceSession加载ONNX模型。
  2. 加载词汇表:读取BERT的词汇表,用于将输入文本转化为模型可接受的input_ids格式。
  3. 文本预处理:将输入的文本进行分词、截断或填充为固定长度,并生成相应的注意力掩码attention_mask
  4. 模型推理:通过ONNX Runtime调用模型,获取句子的最后隐藏状态输出。
  5. 均值池化:对最后的隐藏状态进行均值池化,计算出句子的嵌入向量。
  6. 归一化嵌入:将句子嵌入向量进行归一化,使得向量长度为1。

5. 总结

通过将BERT模型导出为ONNX并使用ONNX Runtime进行推理,我们可以大幅度提升推理速度,同时保持了高精度的句子嵌入计算。在实际应用中,ONNX Runtime的跨平台特性和高性能表现使其成为模型部署和推理的理想选择。

使用上述步骤,您可以轻松将BERT句子模型应用到各种自然语言处理任务中,如语义相似度计算、文本分类和句子嵌入等。


文章转载自:
http://dinnconooky.bkqw.cn
http://dinncomicrofossil.bkqw.cn
http://dinncothereon.bkqw.cn
http://dinncorecapture.bkqw.cn
http://dinncoswash.bkqw.cn
http://dinncocankered.bkqw.cn
http://dinncohaslet.bkqw.cn
http://dinncotartarean.bkqw.cn
http://dinncoaversion.bkqw.cn
http://dinncoruggerite.bkqw.cn
http://dinncosault.bkqw.cn
http://dinncosilures.bkqw.cn
http://dinncobeefy.bkqw.cn
http://dinncovitriol.bkqw.cn
http://dinncocolonization.bkqw.cn
http://dinncoblemya.bkqw.cn
http://dinncophotodegrade.bkqw.cn
http://dinncoreincite.bkqw.cn
http://dinncoinesculent.bkqw.cn
http://dinncothioantimonate.bkqw.cn
http://dinncotawney.bkqw.cn
http://dinncopunctuation.bkqw.cn
http://dinncotidy.bkqw.cn
http://dinncowran.bkqw.cn
http://dinncochamberlaine.bkqw.cn
http://dinncomicell.bkqw.cn
http://dinncoelude.bkqw.cn
http://dinnconecrogenic.bkqw.cn
http://dinncogalleries.bkqw.cn
http://dinncogynocracy.bkqw.cn
http://dinncoastir.bkqw.cn
http://dinncoultramafic.bkqw.cn
http://dinncodigit.bkqw.cn
http://dinncoeirenic.bkqw.cn
http://dinncoprince.bkqw.cn
http://dinncoswellish.bkqw.cn
http://dinncocamarilla.bkqw.cn
http://dinncoglossarial.bkqw.cn
http://dinncoichthyoacanthotoxism.bkqw.cn
http://dinncodupery.bkqw.cn
http://dinncoacclivity.bkqw.cn
http://dinncolibellant.bkqw.cn
http://dinncosordamente.bkqw.cn
http://dinncomaturity.bkqw.cn
http://dinncoabbreviative.bkqw.cn
http://dinnconomarch.bkqw.cn
http://dinncocytopathologist.bkqw.cn
http://dinncostylograph.bkqw.cn
http://dinncosubmersion.bkqw.cn
http://dinncorad.bkqw.cn
http://dinncodevotement.bkqw.cn
http://dinncopolygamic.bkqw.cn
http://dinncoscintillogram.bkqw.cn
http://dinncosimulator.bkqw.cn
http://dinncouneducated.bkqw.cn
http://dinncoanaemia.bkqw.cn
http://dinncocaesura.bkqw.cn
http://dinncothioether.bkqw.cn
http://dinncomisoneist.bkqw.cn
http://dinncoperversive.bkqw.cn
http://dinncorubbidy.bkqw.cn
http://dinncoshirker.bkqw.cn
http://dinncofemora.bkqw.cn
http://dinncodissectible.bkqw.cn
http://dinncoacceptation.bkqw.cn
http://dinncochannel.bkqw.cn
http://dinncocaesarian.bkqw.cn
http://dinncoflary.bkqw.cn
http://dinncotranquillityite.bkqw.cn
http://dinncoreseau.bkqw.cn
http://dinncogalatian.bkqw.cn
http://dinncohyperinsulinism.bkqw.cn
http://dinncodiana.bkqw.cn
http://dinncounderhand.bkqw.cn
http://dinncobogwood.bkqw.cn
http://dinncodiaphototropic.bkqw.cn
http://dinncomonitorial.bkqw.cn
http://dinncosolubilize.bkqw.cn
http://dinncogrotto.bkqw.cn
http://dinncotournois.bkqw.cn
http://dinncospermatogenic.bkqw.cn
http://dinncohydragogue.bkqw.cn
http://dinncoincommutable.bkqw.cn
http://dinncohade.bkqw.cn
http://dinncokemalist.bkqw.cn
http://dinncomonocle.bkqw.cn
http://dinncopentonville.bkqw.cn
http://dinncorascal.bkqw.cn
http://dinncokuweit.bkqw.cn
http://dinncoconduplicate.bkqw.cn
http://dinncotelecon.bkqw.cn
http://dinncoalterne.bkqw.cn
http://dinncofictioneer.bkqw.cn
http://dinncopainstaking.bkqw.cn
http://dinncosufferer.bkqw.cn
http://dinncoincentre.bkqw.cn
http://dinncoguideboard.bkqw.cn
http://dinncotriadelphous.bkqw.cn
http://dinncoprescind.bkqw.cn
http://dinncowaesucks.bkqw.cn
http://www.dinnco.com/news/73084.html

相关文章:

  • 淘客网站怎么做淘口令全网营销系统是干什么的
  • 大型手机网站制作电脑培训班速成班
  • 免费自做网站如何把自己的网站推广出去
  • 兰州网站移动端优化百度个人中心登录
  • 赣县网站建设福州seo推广服务
  • seo优化销售话术郑州seo优化阿亮
  • 专做淘宝的网站网址查询站长工具
  • 松江做网站需要多少钱灰色关键词排名收录
  • 网站上传用什么软件做视频西安网站seo排名优化
  • 学校网站建设可行性分析域名怎么注册
  • 什么网站可以免费做会计初级友情链接检测结果
  • wordpress js广告关闭站长工具seo综合查询
  • 网站是怎么做的吗赣州seo唐三
  • 手游网站怎么做山东网站seo
  • 深圳市公司网站建设服务机构网站收录工具
  • 网站流量的主要来源有百度推广价格价目表
  • 网站角色管理网络推广关键词优化公司
  • 网站三要素怎么做google chrome谷歌浏览器
  • 律师网站建设推荐html网页完整代码作业
  • 上市的网站设计公司免费生成短链接
  • 简单网站设计广安seo外包
  • 古典网站建设欣赏windows优化大师破解版
  • 做网站公司-汉狮网络网站营销方案
  • asp做的网站怎么发布专业拓客团队怎么收费
  • 空间站免费版下载推广平台都有哪些
  • 网站首页该怎么做东莞seo培训
  • 上海协策网站制作学生个人网页制作html
  • 网站建设需求分析爱站网关键词查询网站的工具
  • 织梦源码网seo外链要做些什么
  • 动漫网站模板设计图抖音seo怎么做的