bert-base-chinese另外的加载方法.txt

import os

os.environ'HF_ENDPOINT' = 'https://hf-mirror.com'

import torch

from transformers import pipeline

pipe = pipeline("fill-mask", model="google-bert/bert-base-chinese")

from transformers import AutoTokenizer, AutoModelForMaskedLM

tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-chinese")

model = AutoModelForMaskedLM.from_pretrained("google-bert/bert-base-chinese")

input_text='bert-base-chinese该怎么用?'

inx_text=tokenizer.encode(input_text)

inv_text=tokenizer.convert_ids_to_tokens(inx_text)

with torch.no_grad():

output=model(torch.tensor(inx_text))

print(type(output))

last_hidden=output'logits'

print(last_hidden.shape,last_hidden0)# (1,9,21128)(batch_size,seq_len,d_model)

from transformers import AutoModelForQuestionAnswering

aq=AutoModelForQuestionAnswering.from_pretrained("google-bert/bert-base-chinese")

定义问题和上下文

question = "你好,请问今天天气怎么样?"

context = "今天是晴天,气温适中,非常适合户外活动。"

使用分词器对问题和上下文进行编码

inputs = tokenizer(question, context, return_tensors='pt', \

padding=True, truncation=True)

input_ids = inputs'input_ids'

attention_mask = inputs'attention_mask'

在Transformers库中,模型并不是通过数字本身来识别分割符的,

而是通过分词器(Tokenizer)对输入文本的处理来识别这些特殊标记。

在不计算梯度的情况下进行推理

with torch.no_grad():

aq_outputs =aq(input_ids, attention_mask=attention_mask)

start_inxes=aq_outputs'start_logits'0

end_inxes=aq_outputs'end_logits'0

print(len(start_inxes),len(end_inxes))

start=torch.argmax(start_inxes)

end=torch.argmax(end_inxes)

(question+context)start:end

相关推荐
阿里云大数据AI技术13 分钟前
构建高转化海外电商搜索:阿里云OpenSearch行业算法版的全链路智能优化策略实战
人工智能·搜索引擎
Awu122726 分钟前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
字节跳动视频云技术团队26 分钟前
让 Agent 成为音视频工作台:AI MediaKit CLI + Skill 发布
人工智能·音视频开发
魏祖潇30 分钟前
framework 整合实战——DDD/TDD/SDD 三件套在 framework 仓的真实落地
人工智能·后端
Token炼金师1 小时前
去噪扩散:从随机噪声到高保真图像的数学之路
人工智能·aigc
这个DBA有点耶1 小时前
AI写的SQL跑崩了生产库,这锅谁背?
数据库·人工智能·程序员
阿里云大数据AI技术2 小时前
阿里云 EMR AI 助手正式发布:从问答工具到全栈智能运维助手
运维·人工智能
Larcher2 小时前
从零搭建 MCP 服务——让 AI 拥有无限扩展能力
人工智能·程序员
zzzzzz3103 小时前
你的 AI 写的 React 烂透了?这个 8000+ Star 的开源工具能揪出 90% 的「Agent 屎山」
人工智能
小星AI3 小时前
MCP协议超详细教程,从入门到实战
人工智能