当前位置: 首页 > news >正文

BERT的中文问答系统50

我们将对BERT的中文问答系统48-1代码进行以下改进:
1.增加时间日期和日历功能:在GUI中增加显示当前时间和日期的功能,并提供一个日历组件。
2.增加更多模型类型:增加娱乐、电脑、军事、汽车、植物、科技、历史(朝代、皇帝)、名人、生活(出行、菜品、菜谱、居家),法律、企业、标准等模型的建立、保存和加载。
3.统一使用百度百科:移除360百科的相关代码。
4.完善GUI布局:优化GUI布局,使其更加美观和易用。
以下是改进后的代码:

import os
import json
import jsonlines
import torch
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from transformers import BertModel, BertTokenizer
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import logging
from difflib import SequenceMatcher
from datetime import datetime
import requests
from bs4 import BeautifulSoup
import calendar# 获取项目根目录
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))# 配置日志
LOGS_DIR = os.path.join(PROJECT_ROOT, 'logs')
os.makedirs(LOGS_DIR, exist_ok=True)def setup_logging():log_file = os.path.join(LOGS_DIR, datetime.now().strftime('%Y-%m-%d_%H-%M-%S_羲和.txt'))logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',handlers=[logging.FileHandler(log_file),logging.StreamHandler()])setup_logging()# 数据集类
class XihuaDataset(Dataset):def __init__(self, file_path, tokenizer, max_length=128):self.tokenizer = tokenizerself.max_length = max_lengthself.data = self.load_data(file_path)def load_data(self, file_path):data = []if file_path.endswith('.jsonl'):with jsonlines.open(file_path) as reader:for i, item in enumerate(reader):try:data.append(item)except jsonlines.jsonlines.InvalidLineError as e:logging.warning(f"跳过无效行 {i + 1}: {e}")elif file_path.endswith('.json'):with open(file_path, 'r') as f:try:data = json.load(f)except json.JSONDecodeError as e:logging.warning(f"跳过无效文件 {file_path}: {e}")return datadef __len__(self):return len(self.data)def __getitem__(self, idx):item = self.data[idx]question = item.get('question', '')human_answer = item.get('human_answers', [''])[0]chatgpt_answer = item.get('chatgpt_answers', [''])[0]try:inputs = self.tokenizer(question, return_tensors='pt', padding='max_length', truncation=True, max_length=self.max_length)human_inputs = self.tokenizer(human_answer, return_tensors='pt', padding='max_length', truncation=True, max_length=self.max_length)chatgpt_inputs = self.tokenizer(chatgpt_answer, return_tensors='pt', padding='max_length', truncation=True, max_length=self.max_length)except Exception as e:logging.warning(f"跳过无效项 {idx}: {e}")return self.__getitem__((idx + 1) % len(self.data))return {'input_ids': inputs['input_ids'].squeeze(),'attention_mask': inputs['attention_mask'].squeeze(),'human_input_ids': human_inputs['input_ids'].squeeze(),'human_attention_mask': human_inputs['attention_mask'].squeeze(),'chatgpt_input_ids': chatgpt_inputs['input_ids'].squeeze(),'chatgpt_attention_mask': chatgpt_inputs['attention_mask'].squeeze(),'human_answer': human_answer,'chatgpt_answer': chatgpt_answer}# 获取数据加载器
def get_data_loader(file_path, tokenizer, batch_size=8, max_length=128):dataset = XihuaDataset(file_path, tokenizer, max_length)return DataLoader(dataset, batch_size=batch_size, shuffle=True)# 模型定义
class XihuaModel(torch.nn.Module):def __init__(self, pretrained_model_name='F:/models/bert-base-chinese'):super(XihuaModel, self).__init__()self.bert = BertModel.from_pretrained(pretrained_model_name)self.classifier = torch.nn.Linear(self.bert.config.hidden_size, 1)def forward(self, input_ids, attention_mask):outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)pooled_output = outputs.pooler_outputlogits = self.classifier(pooled_output)return logits# 训练函数
def train(model, data_loader, optimizer, criterion, device, progress_var=None):model.train()total_loss = 0.0num_batches = len(data_loader)for batch_idx, batch in enumerate(data_loader):try:input_ids = batch['input_ids'].to(device)attention_mask = batch['attention_mask'].to(device)human_input_ids = batch['human_input_ids'].to(device)human_attention_mask = batch['human_attention_mask'].to(device)chatgpt_input_ids = batch['chatgpt_input_ids'].to(device)chatgpt_attention_mask = batch['chatgpt_attention_mask'].to(device)optimizer.zero_grad()human_logits = model(human_input_ids, human_attention_mask)chatgpt_logits = model(chatgpt_input_ids, chatgpt_attention_mask)human_labels = torch.ones(human_logits.size(0), 1).to(device)chatgpt_labels = torch.zeros(chatgpt_logits.size(0), 1

相关文章:

BERT的中文问答系统50

我们将对BERT的中文问答系统48-1代码进行以下改进: 1.增加时间日期和日历功能:在GUI中增加显示当前时间和日期的功能,并提供一个日历组件。 2.增加更多模型类型:增加娱乐、电脑、军事、汽车、植物、科技、历史(朝代、皇帝)、名人、生活(出行、菜品、菜谱、居家),法律、…...

深入解析CMake中的find_package命令:用法、特性及版本依赖问题

深入解析CMake中的find_package命令:用法、特性及版本依赖问题 在现代软件开发中,CMake作为一个强大的构建系统,广泛应用于跨平台项目的管理与编译。find_package是CMake中一个核心命令,用于查找并配置项目所依赖的外部库或包。本…...

【OpenDRIVE_Python】使用python脚本输出OpenDRIVE数据中含有隧道tunnel的道路ID和隧道信息

示例代码说明: 遍历OpenDRIVE数据中每条道路Road,若Road中存在隧道tunnel属性,则将该道路ID和包含的所有隧道信息输出到xml文件中。 import xml.dom.minidom from xml.dom.minidom import parse from xml.dom import Node import sys import os # 读取…...

SIP系列五:HTTP(SIP)鉴权

我的音视频/流媒体开源项目(github) SIP系列目录 目录 一、基本认证(basic) 二、摘要认证(digest) 1、摘要认证(digest) RFC 2069​ 2、摘要认证(digest) RFC 2617​ 2.1、未定义qop字段或值为"(空) 2.2、qop值为"auth" 2.3、qop值为"auth-int&quo…...

mysql json整数数组去重 整数数组精确查找并删除相应数据

都是针对整数数组 。低版本可用。懒得去查找资料的可以参考下。 json整数数组查找具体数据修改或者删除: update saas_new_tms.eda_logistics_limit set service_attribute json_remove(service_attribute,json_unquote(json_search(replace(service_attribute,…...

【5G】技术组件 Technology Components

5G的目标设置非常高,不仅在数据速率上要求达到20Gbps,在容量提升上要达到1000倍,还要为诸如大规模物联网(IoT, Internet of Things)和关键通信等新服务提供灵活的平台。这些高目标要求5G网络采用多种新技术…...

数据结构4——栈和队列

目录 1.栈 1.1.栈的概念及结构 1.2栈的实现 2.队列 2.1队列的概念及结构 2.2队列的实现 1.栈 1.1.栈的概念及结构 栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一段称为栈顶,另一端称为…...

PHP SM4 加密

PHP SM4 加密 sm4基类 class Sm4 {private $ck [0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,0xc0c7ced5, 0xdce3ea…...

leetcode - 2825. Make String a Subsequence Using Cyclic Increments

Description You are given two 0-indexed strings str1 and str2. In an operation, you select a set of indices in str1, and for each index i in the set, increment str1[i] to the next character cyclically. That is ‘a’ becomes ‘b’, ‘b’ becomes ‘c’, an…...

工业—使用Flink处理Kafka中的数据_ChangeRecord1

使用 Flink 消费 Kafka 中 ChangeRecord 主题的数据,当某设备 30 秒状态连续为 “ 预警 ” ,输出预警 信息。当前预警信息输出后,最近30...

探索嵌入式硬件设计:揭秘智能设备的心脏

目录 引言 嵌入式系统简介 嵌入式硬件设计的组成部分 设计流程 微控制器选择 原理图设计 PCB布局 编程与调试 系统集成与测试 深入理解微控制器 存储器管理 输入/输出接口 通信接口 电源管理 硬件抽象层(HAL) 操作系统(OS&am…...

数据结构-最小生成树

一.最小生成树的定义 从V个顶点的图里生成的一颗树,这颗树有V个顶点是连通的,有V-1条边,并且边的权值和是最小的,而且不能有回路 二.Prim算法 Prim算法又叫加点法,算法比较适合稠密图 每次把边权最小的顶点加入到树中&#xff0…...

mac启动jmeter

// 设置使用java8,使用21版本会有问题 export JAVA_HOME/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home/ export PATH$JAVA_HOME/bin:$PATH cd /Users/user/software/apache-jmeter-5.1.1 //设置不使用代理 sh jmeter -Jhttp.proxyHost -J…...

spring学习笔记之静态代理和动态代理

在 Spring 开发中,静态代理和动态代理是实现面向切面编程(AOP)的两种常见方式。两者的主要区别在于代理类的生成时间和方式。 静态代理 定义 静态代理是由开发者或工具在编译期明确创建代理类的方式,代理类和目标类在程序运行前就已经存在。 特点 代理类明确存在:需要…...

qemu搭建aarch64

qemu工具搭建aarch64系统 下载准备 下载qemu: https://qemu.weilnetz.de/w64/2022/qemu-w64-setup-20220831.exe 下载固件:https://publishing-ie-linaro-org.s3.amazonaws.com/releases/components/kernel/uefi-linaro/16.02/release/qemu64/QEMU_EFI.fd?Signat…...

delphi IDE 插件DelphiIDEPlugin_SearchProject,用于从项目组中查找项目

delphi IDE 插件DelphiIDEPlugin_SearchProject,用于从项目组中查找项目 安装后在菜单Tools下第一个子菜单项查找项目 delphiIDE插件DelphiIDEPlugin-SearchProject,用于从项目组中查找项目资源-CSDN文库...

【Vue】Scoped、组件间通信、Props检验

目录 Scoped 作用 *原理 组件通信 前置知识 什么是组件通信 为什么需要组件通信 如何进行组件通信 如何辨别两个组件的关系 父子组件通信 父传子 子传父 非父子组件通信 祖先传后代 语法 任意两个组件通信 步骤 Props校验 props是什么 作用 语法 组件的…...

openbmc dbus架构简析(二)

1.说明 以前看内核代码觉得难,是因为内核代码涉及到硬件原理与算法结构和层次递进的代码逻辑,现在的应用层因为业务的复杂与代码和内核的交互接口复杂,也变得有些难度了。 这篇文章是继:openbmc dbus架构简析的第二篇文章。 首先贴出来前篇…...

【二分查找】Leetcode例题

【1】69. x 的平方根 - 力扣&#xff08;LeetCode&#xff09; &#x1f361;解题思路&#xff1a;首先想到的是暴力查找&#xff0c;从1开始依次比较x与num*num的大小&#xff0c;然后找出满足num*num<x且(num1)*(num1)>x的num值&#xff1b;再来看看能不能优化一下&…...

gitlab配置调试minio

官方文档 rails console 调试 查看配置Settings.uploads.object_store加载minio clientrequire fog/awsfog_connection Fog::Storage.new(provider: AWS,aws_access_key_id: 你的MINIO_ACCESS_KEY,aws_secret_access_key: 你的MINIO_SECRET_KEY,region: <S3 region>,e…...

3步释放20GB空间:Windows驱动清理神器完全指南

3步释放20GB空间&#xff1a;Windows驱动清理神器完全指南 【免费下载链接】DriverStoreExplorer Driver Store Explorer 项目地址: https://gitcode.com/gh_mirrors/dr/DriverStoreExplorer 驱动管理痛点分析 系统臃肿的隐形杀手 随着电脑使用时间增长&#xff0c;Wi…...

暗黑破坏神2存档编辑器:安全高效的d2s文件修改与角色属性调整工具

暗黑破坏神2存档编辑器&#xff1a;安全高效的d2s文件修改与角色属性调整工具 【免费下载链接】d2s-editor 项目地址: https://gitcode.com/gh_mirrors/d2/d2s-editor 暗黑破坏神2存档编辑器&#xff08;d2s-editor&#xff09;是一款专为《暗黑破坏神2》玩家设计的开源…...

高效信息检索技巧:构建精准检索式的实战指南

1. 布尔逻辑检索&#xff1a;信息检索的基石 我第一次接触布尔逻辑检索是在大学写论文的时候&#xff0c;当时为了找几篇关于机器学习在医疗领域应用的文献&#xff0c;在数据库里输入"machine learning healthcare"直接搜&#xff0c;结果跳出来上万条结果&#xff…...

django-unfold过滤器系统完全解析:实现高效数据筛选的终极技巧

django-unfold过滤器系统完全解析&#xff1a;实现高效数据筛选的终极技巧 【免费下载链接】django-unfold Modern Django Admin 项目地址: https://gitcode.com/gh_mirrors/dj/django-unfold django-unfold过滤器系统是Modern Django Admin框架中提升数据管理效率的核心…...

颠覆式AI视觉自动化:3大突破重新定义UI测试与跨平台交互

颠覆式AI视觉自动化&#xff1a;3大突破重新定义UI测试与跨平台交互 【免费下载链接】midscene AI-powered, vision-driven UI automation for every platform. 项目地址: https://gitcode.com/GitHub_Trending/mid/midscene 在数字化转型加速的今天&#xff0c;UI自动化…...

PT助手Plus终极配置指南:三步实现智能自动化下载生态

PT助手Plus终极配置指南&#xff1a;三步实现智能自动化下载生态 【免费下载链接】PT-Plugin-Plus PT 助手 Plus&#xff0c;为 Microsoft Edge、Google Chrome、Firefox 浏览器插件&#xff08;Web Extensions&#xff09;&#xff0c;主要用于辅助下载 PT 站的种子。 项目地…...

Hotkey Detective:3分钟快速定位Windows热键冲突的终极指南

Hotkey Detective&#xff1a;3分钟快速定位Windows热键冲突的终极指南 【免费下载链接】hotkey-detective A small program for investigating stolen key combinations under Windows 7 and later. 项目地址: https://gitcode.com/gh_mirrors/ho/hotkey-detective 你是…...

实测联想小新Pro 16 GT:一台把性能、AI和续航拉满的AI PC

最近体验了联想小新Pro 16 GT AI元启版&#xff0c;它不像是传统轻薄本&#xff0c;更像一台兼顾便携、性能和智能体验的全能机型。抛开品牌滤镜&#xff0c;单看硬件和实际使用&#xff0c;确实有不少值得一说的亮点。外观轻薄耐看&#xff0c;屏幕和接口都很实在这台机器用了…...

终端设置显示项目的分支名

function parse_git_branch() {git branch 2> /dev/null | sed -n -e s/^\* \(.*\)/[\1]/p}setopt PROMPT_SUBSTexport PROMPT%F{grey}%n%f %F{green}$(parse_git_branch)%f %F{normal}$%f 在.zshrc中设置以上即可...

基于FireRedASR-AED-L与AIGC技术:自动生成语音错误分析报告

基于FireRedASR-AED-L与AIGC技术&#xff1a;自动生成语音错误分析报告 想象一下这个场景&#xff1a;你的团队刚刚完成了一轮大规模的语音识别系统测试&#xff0c;收集了上千小时的音频数据。接下来&#xff0c;你需要从海量的识别结果中&#xff0c;找出哪些词识别错了&…...