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

相关推荐
jsl_jsl_jsl几秒前
《单机 Agent 应用的可观测性:刻意轻量的日志与调用链实现》
人工智能
G***技几秒前
告别物联网碎片化:杰和LH707+LM2-100-V0联合方案给出标准答案
人工智能·嵌入式硬件
szxinmai主板定制专家1 分钟前
【工控实战】RK3568/RK3588 8路隔离CAN/CANFD完整解决方案|多路总线并行通信、车载/工控量产落地
人工智能·fpga开发·zynq·mpsoc·半导体设备
刘马想放假2 分钟前
RK3588 使用 rk-llama.cpp + RKNPU2 部署 Qwen3.5:从零开始的 NPU 本地大模型实战
人工智能·开源·llm
商业看点解说10 分钟前
哪些 AI 创业公司和生成式 AI 产品适合使用 Amazon Bedrock?
人工智能
智驭未来掌门人11 分钟前
大模型网关集成 MCP 与 CLI 的调用指南(自动分配密钥工具)
人工智能
snakeshe101011 分钟前
AI 应用开发Day4(下):Embedding——从关键词匹配走向语义检索
人工智能
秦先生在广东15 分钟前
Tencent BrowserSkill:让 AI Agent 无缝接入真实浏览器会话
人工智能
Allen正心正念202528 分钟前
Agent框架—LangGraph智能体框架设计要点和踩坑预防指南
人工智能
高升说32 分钟前
无人机机载视觉避障硬件链路拆解:从成像到制动的五层设计
人工智能