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

相关推荐
卡索(CASO)汽车调查1 分钟前
卡索(CASO)汽车调查:数据智能时代,汽车产业竞争格局与战略升维路径探析
大数据·人工智能·汽车·神秘顾客·汽车密采·神秘人·汽车研究
笨鸟笃行5 分钟前
人工智能备考——2.1.1-2.1.5总结
人工智能·学习
晨非辰8 分钟前
【数据结构】排序详解:从快速排序分区逻辑,到携手冒泡排序的算法效率深度评测
运维·数据结构·c++·人工智能·后端·深度学习·排序算法
能来帮帮蒟蒻吗16 分钟前
深度学习(4)—— Pytorch快速上手!从零搭建神经网络
人工智能·pytorch·深度学习
Blossom.11822 分钟前
大模型知识蒸馏实战:从Qwen-72B到Qwen-7B的压缩艺术
大数据·人工智能·python·深度学习·算法·机器学习·pygame
pingao14137837 分钟前
零启动风速+多参数集成:金属超声波传感器的技术突破
人工智能·科技
wshzd1 小时前
LLM之Agent(二十八)|AI音视频转笔记方法揭秘
人工智能·笔记
IT_陈寒1 小时前
Python 3.12新特性实战:5个让你的代码效率翻倍的隐藏技巧!
前端·人工智能·后端
草莓熊Lotso1 小时前
C++ 二叉搜索树(BST)完全指南:从概念原理、核心操作到底层实现
java·运维·开发语言·c++·人工智能·经验分享·c++进阶
Dfreedom.1 小时前
大模型微调技术全景解析:从基础理论到工程实践
人工智能·大模型微调