基于BERT模型进行文本处理(Python)
基于BERT模型进行文本处理(Python)
所有程序都由Python使用Spyder运行。
对于BERT,在运行之前,它需要安装一些环境。
首先,打开Spyder。其次,在控制台中单独放置要安装的:
pip install transformers
pip install torch
pip install torch torchvision
conda install pytorch torchvision torchaudio -c pytorch
第三,重新启动内核(这意味着关闭Spyder并重新打开它)。
最后,直接打开python文件(后面有完整代码和运行之后的结果),点击运行,就可以产生结果。
所有数据都存储在名为data的BERT文件夹中。处理时,它将自动加载数据文件夹。然后它将创建traintest.csv和validation_test.csv。之后,它将分析test文件包,以自动生成test.csv和test-analysis.csv
Bert并不是专门用来确定一份文件是由单个作者还是由多个作者撰写的。这是因为,要确定一份文档是单作者还是多作者,需要了解文档的结构和内容,并分析整个文本中使用的写作风格。
检测文本中的变化可以使用BERT(一种预先训练的语言模型)和逻辑回归分类器来实现。这个过程的第一步是使用BERT对两段文本进行编码。BERT将文本编码为一系列向量,其中每个向量表示文本中的不同单词或子单词。然后,可以使用这些编码向量来训练分类器,以预测两段文本是相似还是不同。
为了训练分类器,有必要为其提供一组标记的训练数据。这意味着我们需要有一组文本对,其中每一对都被标记为相似或不同。这些信息可以从JSON文件中获得,但在这种情况下,我们使用前面在数据中提到的CSV文件中第二列的更改。我们使用这些文本对来训练分类器来识别相似文本和不同文本之间的差异。
一旦分类器经过训练,它就可以用来预测新的文本对的相似性。要做到这一点,首先使用BERT对两段文本进行编码,然后将编码后的表示输入到逻辑回归分类器中。然后,分类器将输出一个介于0和1之间的值,该值表示两段文本相似的概率。为了避免输出只有一个类的情况,使用1乘以段落数作为预测结果来处理每个段落样式不同的特殊情况。
检测作者涉及与标记化不同的方法。用于此任务的方法称为BertForSequenceClassification,它将每个段落分解为一系列标记。参数model_name和num_labels在该方法中至关重要。Model_name用于加载适用于特定任务的预训练BERT模型,而num_labels则指定分类任务中的类数。在这个项目中,num_labels等于文档中的段落数。然后,使用BERT模型将标记嵌入到高维空间中,该模型为每个段落创建一个矢量表示,以捕捉其语义。
然后,通过将嵌入向量序列作为输入,使用监督学习算法来预测通信作者。该模型是在标记的数据集上使用损失函数进行训练的,该函数测量预测作者和真实作者之间的差异。训练后,使用单独的数据集对模型进行验证,以评估其准确性,并进行任何必要的调整以提高其性能。
一旦该模型经过训练和验证,就可以用来预测新文本中单个段落的作者身份。但是,段落作者的最大数量应与段落数量相同。根据文献综述,发现多个作者主要在2到5个之间,因此该项目将段落作者的数量限制在段落总数的1到一半之间。

from sklearn.metrics import f1_score, accuracy_score
from transformers import BertTokenizer, BertForSequenceClassification
import numpy as np
from sklearn.linear_model import LogisticRegression
import transformers
from transformers import BertTokenizer, BertForSequenceClassification
import torch
from collections import defaultdict
#from hmmlearn import hmm
import math
import operator
import numpy as np
import nltk
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenizeimport string
import os
import math
from scipy.stats import chi2_contingency
import pandas as pd
import globimport ast
import json
import csv
import pandas as pd
import re
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression# create a csv that store the related information from tain or validation(depends on the main part)
def createCsv(rout,csv_name):test=[]header = ['id', 'multi-author', 'changes','para_author','paragraph']rout_txt=glob.glob(rout+'/*.txt')rout_json=glob.glob(rout+'/*.json')for n in range(len(rout_txt)):for m in range(len(rout_json)):if(rout_txt[n].split('.')[0].split('-')[-1]==rout_json[m].split('.')[0].split('-')[-1]):with open(rout_txt[n],'r', encoding='utf-8') as f1:print(rout_txt[n])paragraph=f1.readlines()with open(rout_json[m], 'r', encoding='utf-8') as f2:content = json.load(f2)uniqId=rout_json[m].split('.')[0].split('-')[-1]multiauthor=content['multi-author']changes=content['changes']para_author=content['paragraph-authors']csvcontent=(uniqId,multiauthor,changes,para_author,paragraph)test.append(csvcontent)with open(csv_name, 'w', encoding='utf-8',newline='') as file_obj1:writer = csv.writer(file_obj1)writer.writerow(header)writer.writerows(test) def preprocessing(s):words = s.translate(str.maketrans('','',string.punctuation))#remove the content punctuationps = PorterStemmer()word = word_tokenize(ps.stem(words))return word# stremming all the wordsdef preanalysis(text):# Tokenize text into wordstokens = nltk.word_tokenize(text) stop_words = set(stopwords.words('english'))# Remove stop words from tokenized textfiltered_tokens = [word for word in tokens if word.lower() not in stop_words]stemmer = PorterStemmer()stemmed_tokens = [stemmer.stem(word) for word in filtered_tokens]return stemmed_tokens# using google bert
tokenizerchange = transformers.BertTokenizer.from_pretrained('bert-base-uncased')
modelchange = transformers.BertModel.from_pretrained('bert-base-uncased')# change the format of changes so that it could matched to train
def forchanges(changes):cleaned_list = [s.strip("[],' ") for s in changes if s not in [",", " "]]cleaned_list.pop(0)del cleaned_list[-1]cleaned_list.insert(0,1)return cleaned_listdef forchanges1(changes):cleaned_list = [s.strip("[],' ") for s in changes if s not in [",", " "]]return cleaned_list# Define a function to predict the author of new paragraphs
def predict_author(texts, tokenizer, model):predicted_authors = []for text in texts:# Tokenize the input text and convert the labels to PyTorch tensorstokenized_text = tokenizer(text, padding=True, truncation=True, return_tensors='pt')# Forward passoutputs = model(**tokenized_text)# Get the predicted authorpredicted_author = torch.argmax(outputs.logits).item()predicted_authors.append(predicted_author)return predicted_authorsdef extract_features(paragraphs):encoded_inputs = tokenizerchange(paragraphs, padding=True, truncation=True, return_tensors='pt')with torch.no_grad():outputs = modelchange(**encoded_inputs)embeddings = outputs.last_hidden_state.mean(dim=1)return embeddings.numpy()if __name__ == "__main__":rout1 = "data/train"csv_name1 = "train_test.csv"createCsv(rout1, csv_name1)counter=0vectorizer1 = CountVectorizer()#create a new csv file to store real results and predicted resultswith open('test.csv', mode='w', newline='') as result:writer = csv.writer(result)#create a new csv file to store all f1 and accuracywith open('test_analysis.csv', mode='w', newline='') as result1:f1_writer = csv.writer(result1)writer.writerow(['id', 'real-multiauthor','pre-multiauthor','real-changes','pre-changes','real-para_author'])f1_writer.writerow(['id', 'multi-accuracy','changes-f1score','changes-accuracy','para-f1score','para-accuracy'])with open ('validation_test.csv',"r", encoding='utf-8')as csvFile:rows=csv.reader(csvFile) for row in rows: if(counter>0):sentsplit=row[-1].split('\\n')if len(sentsplit) <= 10:sentsplit1= sentsplitelse:sentsplit1 = sentsplit.pop()# load the content inside csvauthors = row[3]changes = row[2]authors1 = ast.literal_eval(authors)multiple = row[1]filename = row[0]if int(filename) not in [71,301,340,642,700,1752, 1823, 2019, 2021, 2022, 2096] and int(filename) <= 1000:#print("filename")#print(filename)print("filename")print(filename)features = extract_features(sentsplit1)cleaned_list = forchanges(changes)#print("correct changes")#print((cleaned_list))# Train a logistic regression model to predict the author of a document based on its BERT embeddingstry:clf1 = LogisticRegression()clf1.fit(features, cleaned_list)test_embedding1 = extract_features(sentsplit1)predicted_changes1 = clf1.predict(test_embedding1)sumchange= sum(int(x) for x in predicted_changes1)#criteria = predicted_changes1.count('1')print('Number of segments with style changes:', sumchange)if sumchange == 1:multiauthor = 0else:multiauthor = 1#print("predict multiauthor")#print(multiauthor)#print("authors")#print(multiple)if int(multiauthor) == int(multiple):multiauthorf1 = 1print(f"F1 score of multiauthor: {multiauthorf1:.2f}")else:multiauthorf1 = 0print(f"F1 score of multiauthor: {multiauthorf1:.2f}")changesf1 = f1_score(cleaned_list, predicted_changes1,pos_label='1')changesac = accuracy_score(cleaned_list, predicted_changes1)#print(f"F1 score of change: {changesf1:.2f}")except Exception as e:print(f"Error occurred: {e}")#changesf1 = (1/len(sentsplit1))#print(f"F1 score of change: {changesf1:.2f}")multiauthor = 1#print("multiauthor")#print(multiauthor)#print("authors")#print(multiple)if int(multiauthor) == int(multiple):multiauthorf1 = 1print(f"F1 score of multiauthor: {multiauthorf1:.2f}")else:multiauthorf1 = 0print(f"F1 score of multiauthor: {multiauthorf1:.2f}")changesf1 = 0changesac = (1/len(sentsplit1))num_authors = (len(sentsplit1))# load pre-trained BERT model and tokenizermodel_name = 'bert-base-uncased'tokenizer = BertTokenizer.from_pretrained(model_name)model = BertForSequenceClassification.from_pretrained(model_name, num_labels=num_authors)# map paragraph indices to author indicesauthor_mapping = authors1if len(author_mapping) < len(sentsplit1):author_mapping += [author_mapping[-1]] * (len(sentsplit1) - len(author_mapping)) new_paragraphs = sentsplit1# tokenize input paragraphsinput_paragraphs = []for paragraph in new_paragraphs:inputs = tokenizer.encode_plus(paragraph, add_special_tokens=True, return_tensors='pt')input_paragraphs.append(inputs)# predict authors of new paragraphspredicted_authors = []for i in range(1, len(input_paragraphs)):# concatenate previous paragraph with current paragraphinputs = input_paragraphs[i].copy()inputs['input_ids'] = torch.cat([inputs['input_ids'], input_paragraphs[i]['input_ids']], dim=1)inputs['token_type_ids'] = torch.cat([inputs['token_type_ids'], input_paragraphs[i]['token_type_ids']], dim=1)inputs['attention_mask'] = torch.cat([inputs['attention_mask'], input_paragraphs[i]['attention_mask']], dim=1)# predict author using BERToutputs = model(**inputs)probabilities = torch.softmax(outputs.logits, dim=1)[0].tolist()# choose author based on maximum probabilitypredicted_author = author_mapping[i] # default to known authormax_prob = probabilities[author_mapping[i]-1] # probability of known authorfor j in range(1,int((len(authors1))/2)):if j != author_mapping[i] and probabilities[j] > max_prob:predicted_author = j+1max_prob = probabilities[j]predicted_authors.append(predicted_author)# add first author to predicted author listpredicted_authors.insert(0, 1)print("Predicted authors:", predicted_authors)print(authors1)f1 = f1_score(authors1, predicted_authors, average='weighted')print(f"F1 score: {f1:.2f}")accuracy = accuracy_score(authors1, predicted_authors)writer.writerow([filename,multiple,multiauthor,cleaned_list,predicted_changes1,authors1,predicted_authors ])f1_writer.writerow([filename,multiauthorf1,changesf1,changesac,f1,accuracy ])counter+=1
使用BERT和文本文件夹中的输入txt文件的结果存储在test.csv和test_analysis.csv中。文件test.csv由与三个任务相关的真实结果和预测结果组成。每个列的名称都提供了其内容的清晰指示,每个属性的内容可以在下面看到:


基于之前的分析,逻辑回归在三项任务中表现良好,执行时间最低。然而,仍然存在一些提高准确性的促销活动。当有四个以上的作者时,检测所有作者是很困难的,当只有一个段落是由另一个作者写的时,识别格式也是很有挑战性的。
解决这些问题的一种可能方法是探索更先进的特征提取技术,例如深度学习模型。此外,结合其他语言特征或元数据(如写作风格或文档结构)以提高检测的准确性可能是有益的。
此外,研究组合多个模型的输出以提高整体性能的集成方法可能是有用的。最后,结合用户反馈或手动验证可以帮助进一步细化检测结果并提高准确性。
相关文章:
基于BERT模型进行文本处理(Python)
基于BERT模型进行文本处理(Python) 所有程序都由Python使用Spyder运行。 对于BERT,在运行之前,它需要安装一些环境。 首先,打开Spyder。其次,在控制台中单独放置要安装的: pip install transformers pip install tor…...
妙鸭相机功能代码复现
妙鸭相机功能代码复现 妙鸭相机主要实现人脸替换与人脸高清增强修复功能。可通过两种方式实现Roop和Lora模型。 RooP笔记 基础模型:inswapper_128.onnx 人脸分析模型:insightface 高清增强模型:gfpgan 大体流程为通过insightface检测出人脸,替换人脸,使用gfpgan对人…...
使用Java Spring Boot构建高效的爬虫应用
本文将介绍如何使用Java Spring Boot框架来构建高效的爬虫应用程序。通过使用Spring Boot和相关的依赖库,我们可以轻松地编写爬虫代码,并实现对指定网站的数据抓取和处理。本文将详细介绍使用Spring Boot和Jsoup库进行爬虫开发的步骤,并提供一…...
归并排序与非比较排序详解
W...Y的主页 😊 代码仓库分享 💕 🍔前言: 上篇博客我们讲解了非常重要的快速排序,相信大家已经学会了。最后我们再学习一种特殊的排序手法——归并排序。话不多说我们直接上菜。 目录 归并排序 基本思想 递归思路…...
第85步 时间序列建模实战:CNN回归建模
基于WIN10的64位系统演示 一、写在前面 这一期,我们介绍CNN回归。 同样,这里使用这个数据: 《PLoS One》2015年一篇题目为《Comparison of Two Hybrid Models for Forecasting the Incidence of Hemorrhagic Fever with Renal Syndrome i…...
【MATLAB源码-第36期】matlab基于BD,SVD,ZF,MMSE,MF,SLNR预编码的MIMO系统误码率分析。
1、算法描述 1. MIMO (多输入多输出):这是一个无线通信系统中使用的技术,其中有多个发送和接收天线。通过同时发送和接收多个数据流,MIMO可以增加数据速率和系统容量,同时提高信号的可靠性。 2. BD (块对角化):这是一…...
Uniapp 新手专用 抖音登录 获取用户头像、名称、openid、unionid、anonymous_openid、session_key
TC-dylogin 一定请选择 源码授权版 教程 第一步 将代码拷贝至您所需要的页面 该代码位置:pages/index.vue 第二步 修改appid和secret 第三步 获取appid和secret 获取appid和secret链接 注意事项 为了安全,我将默认的自己的appid和secret在云函数中删…...
openssl引擎开发踩坑小记
前言 在开发openssl引擎过程中,引擎莫名其妙的加载不上,错误如下图: 大概意思就是加载引擎动态库时失败了。 在网上一顿搜索后,也没找到想要的答案。 原因 许多引擎都是基于第三方动态库开发的,引擎本身在开发时&a…...
ubuntu 设置x11vnc服务
Ubuntu 18.04 设置x11vnc服务 自带的vino-server也可以用但是不好用,在ubuntu论坛上看见推荐的x11vnc(ubuntu关于vnc的帮助页面),使用设置一下,结果发现有一些坑需要填,所以写下来方便下次使用 转载请说明…...
物理备份xtrabackup
物理备份: 直接复制数据库文件,适用于大型数据库环境,不受存储引擎的限制,但不能恢复到不同的MySQL版本。 1.完全备份-----完整备份: 每次都将所有数据(不管自第一次备份以来有没有修改过)&am…...
1.springcloudalibaba nacos2.2.3部署
前言 nacos是springcloudalibaba体系的注册中心,演示如何搭建最新稳定版本的linux搭建。 前置条件,安装好jdk1.8 一、二进制压缩包下载 1.1 下载压缩包 nacos下载 点击下载下载后得到二进制包如下 nacos-2.2.3.tar.gz二、安装步骤 2.1.解压二进制…...
Linux 查看是否安装memcached
telnet 127.0.0.1 11211这样的命令连接上memcache,然后直接输入stats就可以得到memcache服务器的版本 安装memcached : sudo apt-get install memcached...
设计模式14、命令模式 Command
解释说明:命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传递给调用对象。调用对象寻找可以处理该命令的合适对象,并把该命令传给相应的对象&…...
【Go】excelize库实现excel导入导出封装(一),自定义导出样式、隔行背景色、自适应行高、动态导出指定列、动态更改表头
前言 最近在学go操作excel,毕竟在web开发里,操作excel是非常非常常见的。这里我选择用 excelize 库来实现操作excel。 为了方便和通用,我们需要把导入导出进行封装,这样以后就可以很方便的拿来用,或者进行扩展。 我参…...
【开发篇】二十、SpringBoot整合RocketMQ
文章目录 1、整合2、消息的生产3、消费4、发送异步消息5、补充:安装RocketMQ 1、整合 首先导入起步依赖,RocketMQ的starter不是Spring维护的,这一点从starter的命名可以看出来(不是spring-boot-starter-xxx,而是xxx-s…...
OpenCV实现求解单目相机位姿
单目相机通过对极约束来求解相机运动的位姿。参考了ORBSLAM中单目实现的代码,这里用opencv来实现最简单的位姿估计. mLeftImg cv::imread(lImg, cv::IMREAD_GRAYSCALE); mRightImg cv::imread(rImg, cv::IMREAD_GRAYSCALE); cv::Ptr<ORB> OrbLeftExtractor …...
深入解析PostgreSQL:命令和语法详解及使用指南
文章目录 摘要引言基本操作安装与配置连接和退出 数据库操作创建数据库删除数据库切换数据库 表操作创建表删除表插入数据查询数据更新数据删除数据 索引和约束创建索引创建约束 用户管理创建用户授权用户修改用户密码 备份和恢复备份数据库恢复数据库 高级特性结语参考文献 摘…...
Elasticsearch数据搜索原理
Elasticsearch 是一个开源的、基于 Lucene 的分布式搜索和分析引擎,设计用于云计算环境中,能够实现实时的、可扩展的搜索、分析和探索全文和结构化数据。它具有高度的可扩展性,可以在短时间内搜索和分析大量数据。 Elasticsearch 不仅仅是一个…...
vue模版语法-{{}}/v-text/v-html/v-once
一、{{}}双括号:用于文本渲染 1、 {{变量名}}:data中返回对象的变量名 2、{{js表达式}}:可以直接进行js表达式处理 3、注意:双大括号中不要写等式书写 二、v-text 指令,用于文本渲染 1、为了解决双大括号渲染数据出现闪烁问题 三、v-cloak …...
前端埋点上传
没事看看: 从用户行为到数据:数据采集全景解析 | 人人都是产品经理 搭建前端监控,采集用户行为的 N 种姿势-前端监控设备 创业公司做数据分析(三)用户行为数据采集系统-CSDN博客...
树莓派超全系列教程文档--(62)使用rpicam-app通过网络流式传输视频
使用rpicam-app通过网络流式传输视频 使用 rpicam-app 通过网络流式传输视频UDPTCPRTSPlibavGStreamerRTPlibcamerasrc GStreamer 元素 文章来源: http://raspberry.dns8844.cn/documentation 原文网址 使用 rpicam-app 通过网络流式传输视频 本节介绍来自 rpica…...
day52 ResNet18 CBAM
在深度学习的旅程中,我们不断探索如何提升模型的性能。今天,我将分享我在 ResNet18 模型中插入 CBAM(Convolutional Block Attention Module)模块,并采用分阶段微调策略的实践过程。通过这个过程,我不仅提升…...
2024年赣州旅游投资集团社会招聘笔试真
2024年赣州旅游投资集团社会招聘笔试真 题 ( 满 分 1 0 0 分 时 间 1 2 0 分 钟 ) 一、单选题(每题只有一个正确答案,答错、不答或多答均不得分) 1.纪要的特点不包括()。 A.概括重点 B.指导传达 C. 客观纪实 D.有言必录 【答案】: D 2.1864年,()预言了电磁波的存在,并指出…...
渲染学进阶内容——模型
最近在写模组的时候发现渲染器里面离不开模型的定义,在渲染的第二篇文章中简单的讲解了一下关于模型部分的内容,其实不管是方块还是方块实体,都离不开模型的内容 🧱 一、CubeListBuilder 功能解析 CubeListBuilder 是 Minecraft Java 版模型系统的核心构建器,用于动态创…...
工程地质软件市场:发展现状、趋势与策略建议
一、引言 在工程建设领域,准确把握地质条件是确保项目顺利推进和安全运营的关键。工程地质软件作为处理、分析、模拟和展示工程地质数据的重要工具,正发挥着日益重要的作用。它凭借强大的数据处理能力、三维建模功能、空间分析工具和可视化展示手段&…...
【android bluetooth 框架分析 04】【bt-framework 层详解 1】【BluetoothProperties介绍】
1. BluetoothProperties介绍 libsysprop/srcs/android/sysprop/BluetoothProperties.sysprop BluetoothProperties.sysprop 是 Android AOSP 中的一种 系统属性定义文件(System Property Definition File),用于声明和管理 Bluetooth 模块相…...
算法岗面试经验分享-大模型篇
文章目录 A 基础语言模型A.1 TransformerA.2 Bert B 大语言模型结构B.1 GPTB.2 LLamaB.3 ChatGLMB.4 Qwen C 大语言模型微调C.1 Fine-tuningC.2 Adapter-tuningC.3 Prefix-tuningC.4 P-tuningC.5 LoRA A 基础语言模型 A.1 Transformer (1)资源 论文&a…...
【学习笔记】erase 删除顺序迭代器后迭代器失效的解决方案
目录 使用 erase 返回值继续迭代使用索引进行遍历 我们知道类似 vector 的顺序迭代器被删除后,迭代器会失效,因为顺序迭代器在内存中是连续存储的,元素删除后,后续元素会前移。 但一些场景中,我们又需要在执行删除操作…...
通过 Ansible 在 Windows 2022 上安装 IIS Web 服务器
拓扑结构 这是一个用于通过 Ansible 部署 IIS Web 服务器的实验室拓扑。 前提条件: 在被管理的节点上安装WinRm 准备一张自签名的证书 开放防火墙入站tcp 5985 5986端口 准备自签名证书 PS C:\Users\azureuser> $cert New-SelfSignedCertificate -DnsName &…...
MySQL 主从同步异常处理
阅读原文:https://www.xiaozaoshu.top/articles/mysql-m-s-update-pk MySQL 做双主,遇到的这个错误: Could not execute Update_rows event on table ... Error_code: 1032是 MySQL 主从复制时的经典错误之一,通常表示ÿ…...
