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

相关推荐
一切皆有可能!!1 小时前
实践篇:利用ragas在自己RAG上实现LLM评估②
人工智能·语言模型
月白风清江有声3 小时前
爆炸仿真的学习日志
人工智能
华奥系科技4 小时前
智慧水务发展迅猛:从物联网架构到AIoT系统的跨越式升级
人工智能·物联网·智慧城市
R²AIN SUITE4 小时前
MCP协议重构AI Agent生态:万能插槽如何终结工具孤岛?
人工智能
b***25114 小时前
动力电池点焊机:驱动电池焊接高效与可靠的核心力量|比斯特自动化
人工智能·科技·自动化
Gyoku Mint5 小时前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
小和尚同志5 小时前
通俗易懂的 MCP 概念入门
人工智能·aigc
dudly5 小时前
大语言模型评测体系全解析(下篇):工具链、学术前沿与实战策略
人工智能·语言模型
zzlyx995 小时前
AI大数据模型如何与thingsboard物联网结合
人工智能·物联网
说私域6 小时前
定制开发开源AI智能名片驱动下的海报工厂S2B2C商城小程序运营策略——基于社群口碑传播与子市场细分的实证研究
人工智能·小程序·开源·零售