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

相关推荐
feng995202 小时前
技术伦理双轨认证如何重构AI工程师能力评估体系——基于AAIA框架的技术解析与行业实证研究
人工智能·aaif·aaia·iaaai
2301_776681652 小时前
【用「概率思维」重新理解生活】
开发语言·人工智能·自然语言处理
蜡笔小新..2 小时前
从零开始:用PyTorch构建CIFAR-10图像分类模型达到接近1的准确率
人工智能·pytorch·机器学习·分类·cifar-10
富唯智能3 小时前
转运机器人可以绕障吗?
人工智能·智能机器人·转运机器人
沅_Yuan3 小时前
基于小波神经网络(WNN)的回归预测模型【MATLAB】
深度学习·神经网络·matlab·回归·小波神经网络·wnn
视觉语言导航4 小时前
湖南大学3D场景问答最新综述!3D-SQA:3D场景问答助力具身智能场景理解
人工智能·深度学习·具身智能
AidLux4 小时前
端侧智能重构智能监控新路径 | 2025 高通边缘智能创新应用大赛第三场公开课来袭!
大数据·人工智能
引量AI4 小时前
TikTok矩阵运营干货:从0到1打造爆款矩阵
人工智能·矩阵·自动化·tiktok矩阵·海外社媒
Hi-Dison4 小时前
神经网络极简入门技术分享
人工智能·深度学习·神经网络
奋斗者1号4 小时前
机器学习之决策树模型:从基础概念到条件类型详解
人工智能·决策树·机器学习