本地部署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 小时前
【文献阅读】当代MOF与机器学习
人工智能·机器学习
来酱何人7 小时前
实时NLP数据处理:流数据的清洗、特征提取与模型推理适配
人工智能·深度学习·分类·nlp·bert
sensen_kiss7 小时前
INT301 Bio-computation 生物计算(神经网络)Pt.3 梯度下降与Sigmoid激活函数
人工智能·神经网络·机器学习
Shilong Wang7 小时前
MLE, MAP, Full Bayes
人工智能·算法·机器学习
Theodore_10227 小时前
机器学习(6)特征工程与多项式回归
深度学习·算法·机器学习·数据分析·多项式回归
数据库知识分享者小北7 小时前
云栖重磅|瑶池数据库:从云原生数据底座向“AI就绪”的多模态数据底座演进
数据库·人工智能·云原生
lingling0097 小时前
机械臂动作捕捉系统选型指南:从需求到方案,NOKOV 度量光学动捕成优选
人工智能·算法
Blossom.1188 小时前
把AI“刻”进玻璃:基于飞秒激光量子缺陷的随机数生成器与边缘安全实战
人工智能·python·单片机·深度学习·神经网络·安全·机器学习
tangchen。8 小时前
YOLOv3 :目标检测的经典融合与创新
人工智能·计算机视觉·目标跟踪
掘金安东尼8 小时前
OCR的新高度?PaddleOCR-VL 与 DeepSeek-OCR 的技术与应用横评
人工智能