本地部署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

相关推荐
Tianyanxiao1 分钟前
【探商宝】2025年2月科技与商业热点头条:AI竞赛、量子计算与芯片市场新格局
大数据·人工智能·经验分享·数据分析
qq_153214526433 分钟前
Openai Dashboard可视化微调大语言模型
人工智能·语言模型·自然语言处理·chatgpt·nlp·gpt-3·transformer
青松@FasterAI1 小时前
【Arxiv 大模型最新进展】PEAR: 零额外推理开销,提升RAG性能!(★AI最前线★)
人工智能
huoyingcg1 小时前
武汉火影数字|VR沉浸式空间制作 VR大空间打造
人工智能·科技·vr·虚拟现实·增强现实
冷冷清清中的风风火火1 小时前
本地部署DeepSeek的硬件配置建议
人工智能·ai
sauTCc1 小时前
RAG实现大致流程
人工智能·知识图谱
lqqjuly2 小时前
人工智能驱动的自动驾驶:技术解析与发展趋势
人工智能·机器学习·自动驾驶
山东布谷科技官方2 小时前
AI大模型发展对语音直播交友系统源码开发搭建的影响
人工智能·实时音视频·交友
thinkMoreAndDoMore2 小时前
深度学习(2)-深度学习关键网络架构
人工智能·深度学习·机器学习
紫雾凌寒2 小时前
计算机视觉基础|从 OpenCV 到频域分析
深度学习·opencv·计算机视觉·傅里叶变换·频域分析