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

相关推荐
AKAMAI1 分钟前
Akamai Cloud客户案例 | IPPRA的简洁、经济、易用的云计算服务
人工智能·云计算
Exploring26 分钟前
从零搭建使用 Open-AutoGML 搜索附近的美食
android·人工智能
阿里云大数据AI技术39 分钟前
在 DataWorks 中一键部署大模型,即刻用于数据集成和数据开发
人工智能
AI科技星1 小时前
质量定义方程常数k = 4π m_p的来源、推导与意义
服务器·数据结构·人工智能·科技·算法·机器学习·生活
机器之心1 小时前
OpenAI推出全新ChatGPT Images,奥特曼亮出腹肌搞宣传
人工智能·openai
机器之心1 小时前
SIGGRAPH Asia 2025:摩尔线程赢图形顶会3DGS挑战赛大奖,自研LiteGS全面开源
人工智能·openai
_Stellar1 小时前
从输入到输出:大语言模型一次完整推理简单解析
人工智能·语言模型·自然语言处理
【建模先锋】1 小时前
特征提取+概率神经网络 PNN 的轴承信号故障诊断模型
人工智能·深度学习·神经网络·信号处理·故障诊断·概率神经网络·特征提取
轲轲011 小时前
Week02 深度学习基本原理
人工智能·深度学习