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

相关推荐
吴佳浩25 分钟前
GPU 编号进阶:CUDA\_VISIBLE\_DEVICES、多进程与容器化陷阱
人工智能·pytorch·python
吴佳浩44 分钟前
GPU 编号错乱踩坑指南:PyTorch cuda 编号与 nvidia-smi 不一致
人工智能·pytorch·nvidia
小饕1 小时前
苏格拉底式提问对抗315 AI投毒:实操指南
网络·人工智能
卧蚕土豆1 小时前
【有啥问啥】OpenClaw 安装与使用教程
人工智能·深度学习
GoCodingInMyWay1 小时前
开源好物 26/03
人工智能·开源
AI科技星1 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
zhangfeng11331 小时前
Windows 的 Git Bash 中使用 md5sum 命令非常简单 md5做文件完整性检测 WinRAR 可以计算文件的 MD5 值
人工智能·windows·git·bash
monsion2 小时前
OpenCode 学习指南
人工智能·vscode·架构
藦卡机器人2 小时前
中国工业机器人发展现状
大数据·人工智能·机器人
破阵子443282 小时前
小米AI新模型全面解析:从MiMo-V2系列到使用指南
人工智能