本地部署bert-base-chinese模型交互式问答,gradio

首先下载bert-base-chinese,可以在 Huggingface, modelscope, github下载

pip install gradio torch transformers

python 复制代码
import gradio as gr
import torch
from transformers import BertTokenizer, BertForQuestionAnswering

# 加载bert-base-chinese模型和分词器
model_name = "D:/dev/php/magook/trunk/server/learn-python/models/bert-base-chinese"
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForQuestionAnswering.from_pretrained(model_name)


def question_answering(context, question):
    # 使用分词器对输入进行处理
    inputs = tokenizer(question, context, return_tensors="pt")
    # 调用模型进行问答
    outputs = model(**inputs)
    # 获取答案的起始和结束位置
    start_scores = outputs.start_logits
    end_scores = outputs.end_logits
    # 获取最佳答案
    answer_start = torch.argmax(start_scores)
    answer_end = torch.argmax(end_scores) + 1
    answer = tokenizer.decode(inputs["input_ids"][0][answer_start:answer_end])
    return answer


# 创建Gradio界面
interface = gr.Interface(
    fn=question_answering,
    inputs=["text", "text"],  # 输入分别为context和question
    outputs="text",  # 输出为答案
)

interface.launch()

运行

bash 复制代码
> python llm_and_transformer/bert/use_bert-base-chinese4.py
Some weights of BertForQuestionAnswering were not initialized from the model checkpoint at D:/dev/php/magook/trunk/server/learn-python/models/bert-base-chinese and are
newly initialized: ['qa_outputs.bias', 'qa_outputs.weight']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.

访问 http://127.0.0.1:7860

相关推荐
万行7 分钟前
SQL进阶&索引篇
开发语言·数据库·人工智能·sql
名字不好奇9 分钟前
一文拆解MCP协议
人工智能·mcp
乾元13 分钟前
拒绝服务的进化:AI 调度下的分布式协同攻击策略
人工智能·分布式
困死,根本不会14 分钟前
OpenCV摄像头实时处理:从单特征到联合识别(形状识别 + 颜色识别 + 形状颜色联合识别)
人工智能·opencv·计算机视觉
工具人呵呵15 分钟前
[嵌入式AI从0开始到入土]22_基于昇腾310P RC模式的ACT模型部署实践
人工智能
yj_sharing16 分钟前
PyTorch深度学习实战:从模型构建到训练技巧
人工智能·pytorch·深度学习
安全二次方security²17 分钟前
CUDA C++编程指南(7.31&32&33&34)——C++语言扩展之性能分析计数器函数和断言、陷阱、断点函数
c++·人工智能·nvidia·cuda·断点·断言·性能分析计数器函数
bksheng19 分钟前
【Dify】安装与部署
人工智能
狸奴算君19 分钟前
告别数据泄露:三步构建企业级AI的隐私保护盾
人工智能
Christo326 分钟前
TKDE-2026《Efficient Co-Clustering via Bipartite Graph Factorization》
人工智能·算法·机器学习·数据挖掘