使用Transformer进行抄袭检测

news2024/10/6 6:03:10

动机

在许多行业中,尤其是在学术界,抄袭是一个重大问题。随着互联网和开放信息的兴起,这种现象甚至变得更加严重,任何人都可以通过点击访问特定主题的任何信息。

基于这一观察,研究人员一直在尝试使用不同的文本分析方法解决这个问题。在这篇概念文章中,我们将尝试解决抄袭检测工具的两个主要限制:(1)内容改写抄袭和(2)内容翻译抄袭。

(1) 对于传统工具来说,重新表述的内容可能很难捕捉到,因为它们没有考虑整体上下文的同义词和反义词。

(2) 使用与原文不同语言编写的内容也是一个巨大的问题,即使是最先进的基于机器学习的工具也面临着这个问题,因为上下文完全转移到了另一种语言。

在这篇概念性的博客文章中,我们将解释如何使用基于Transformer的模型以创新的方式解决这两个挑战。

首先,我们将带你了解分析方法,描述从数据收集到性能分析的整个工作流程。然后,我们将深入探讨解决方案的科学/技术实现,然后展示最终结果。

问题陈述

假设你有兴趣构建一个学术内容管理平台。你可能希望只接受在你的平台上没有共享过的文章。在这种情况下,你的目标将是拒绝所有与现有文章相似度超过某个阈值的新文章。

为了说明这种情况,我们将使用cord-19数据集,这是由Allen Institute for AI在Kaggle上免费提供的开放研究挑战数据集。

https://allenai.org/

分析方法

在进一步进行分析之前,让我们从以下问题明确我们在这里试图实现的目标:

问题:我们能否在我们的数据库中找到一个或多个与新提交的文档相似(超过某个阈值)的文档?

下面的工作流程突出显示了回答这个问题所需的所有主要步骤。

让我们了解这里正在发生的事情 💡。

在收集源数据后,我们首先对内容进行预处理,然后使用BERT创建一个向量数据库。

然后,每当我们有一个新的文档进入时,我们检查语言并进行抄袭检测。更多详细信息将在文章后面给出。

科学实施

本节专注于分析方法中各个部分的技术实施。

数据预处理

我们只对源数据的摘要列感兴趣,为了简单起见,我们将仅使用100个观察结果来加快预处理的速度。

import pandas as pd  
  
def preprocess_data(data_path, sample_size):  
  
  # Read the data from specific path  
  data = pd.read_csv(data_path, low_memory=False)  
  
  # Drop articles without Abstract  
  data = data.dropna(subset = ['abstract']).reset_index(drop = True)  
  
  # Get "sample_size" random articles  
  data = data.sample(sample_size)[['abstract']]  
  
  return data  
  
# Read data & preprocess it  
data_path = "./data/cord19_source_data.csv"  
source_data = preprocess_data(data_path, 100)  

以下是源数据集的五个随机观察结果。

文档向量化器

在引言中观察到的挑战分别导致选择以下两个基于Transformer的模型:

(1) BERT模型:用于解决第一个限制,因为它提供了文本信息更好的上下文表示。为此,我们将使用以下功能:

  • create_vector_from_text:用于生成单个文档的向量表示。

  • create_vector_database:负责创建一个数据库,其中包含每个文档的相应向量。

# Useful libraries  
import numpy as np  
import torch  
from keras.preprocessing.sequence import pad_sequences  
from transformers import BertTokenizer,  AutoModelForSequenceClassification  
  
# Load bert model  
model_path = "bert-base-uncased"  
  
tokenizer = BertTokenizer.from_pretrained(model_path,   
                                          do_lower_case=True)  
  
model = AutoModelForSequenceClassification.from_pretrained(model_path,  
                                                          output_attentions=False,  
                                                          output_hidden_states=True)  
  
  
def create_vector_from_text(tokenizer, model, text, MAX_LEN = 510):  
  
    input_ids = tokenizer.encode(  
                        text,   
                        add_special_tokens = True,   
                        max_length = MAX_LEN,                             
                   )      
  
    results = pad_sequences([input_ids], maxlen=MAX_LEN, dtype="long",   
                              truncating="post", padding="post")  
  
    # Remove the outer list.  
    input_ids = results[0]  
  
    # Create attention masks      
    attention_mask = [int(i>0) for i in input_ids]  
  
    # Convert to tensors.  
    input_ids = torch.tensor(input_ids)  
    attention_mask = torch.tensor(attention_mask)  
  
    # Add an extra dimension for the "batch" (even though there is only one   
    # input in this batch.)  
    input_ids = input_ids.unsqueeze(0)  
    attention_mask = attention_mask.unsqueeze(0)  
  
    # Put the model in "evaluation" mode, meaning feed-forward operation.  
    model.eval()  
  
    # Run the text through BERT, and collect all of the hidden states produced  
    # from all 12 layers.   
    with torch.no_grad():          
        logits, encoded_layers = model(  
                                    input_ids = input_ids,   
                                    token_type_ids = None,   
                                    attention_mask = attention_mask,  
                                    return_dict=False)  
  
    layer_i = 12 # The last BERT layer before the classifier.  
    batch_i = 0 # Only one input in the batch.  
    token_i = 0 # The first token, corresponding to [CLS]  
  
    # Extract the vector.  
    vector = encoded_layers[layer_i][batch_i][token_i]  
  
    # Move to the CPU and convert to numpy ndarray.  
    vector = vector.detach().cpu().numpy()  
  
    return(vector)  
  
  
def create_vector_database(data):  
  
    # The list of all the vectors  
    vectors = []  
  
    # Get overall text data  
    source_data = data.abstract.values  
  
    # Loop over all the comment and get the embeddings  
    for text in tqdm(source_data):  
  
        # Get the embedding   
        vector = create_vector_from_text(tokenizer, model, text)  
  
        #add it to the list  
        vectors.append(vector)  
  
    data["vectors"] = vectors  
    data["vectors"] = data["vectors"].apply(lambda emb: np.array(emb))  
    data["vectors"] = data["vectors"].apply(lambda emb: emb.reshape(1, -1))  
  
    return data  
  
# Create the vector database   
vector_database = create_vector_database(source_data)  
vector_database.sample(5)  

第94行显示了向量数据库中的五个随机观察结果,包括新向量列。

(2) 使用机器翻译Transformer模型将传入文档的语言翻译为英语,因为我们的源文档是英文的。只有当文档的语言是以下五种语言之一时,才执行翻译:德语、法语、日语、希腊语和俄语。以下是使用MarianMT模型实现此逻辑的辅助函数。

from langdetect import detect, DetectorFactory  
DetectorFactory.seed = 0  
  
def translate_text(text, text_lang, target_lang='en'):  
  
  # Get the name of the model  
  model_name = f"Helsinki-NLP/opus-mt-{text_lang}-{target_lang}"  
  
  # Get the tokenizer  
  tokenizer = MarianTokenizer.from_pretrained(model_name)  
  
  # Instantiate the model  
  model = MarianMTModel.from_pretrained(model_name)  
  
  # Translation of the text  
  formated_text = ">>{}<< {}".format(text_lang, text)  
  
  translation = model.generate(**tokenizer([formated_text], return_tensors="pt", padding=True))  
  
  translated_text = [tokenizer.decode(t, skip_special_tokens=True) for t in translation][0]  
  
  return translated_text  

抄袭分析器

当传入文档的向量与数据库中的某个向量在一定阈值水平上相似时,就存在抄袭。

但是,什么时候两个向量是相似的?→ 当它们具有相同的大小和方向时。

这个定义要求我们的向量具有相同的大小,这可能是一个问题,因为文档向量的维度取决于该文档的长度。幸运的是,我们有多种相似度测量方法可以用来解决这个问题,其中之一就是余弦相似度,我们将在本例中使用它。

如果你对其他方法感兴趣,可以参考James Briggs的这篇精彩内容。他解释了每种方法的工作原理、优点,并指导你如何实施它们。

https://www.pinecone.io/learn/semantic-search/

抄袭分析是使用run_plagiarism_analysis函数执行的。我们首先使用check_incoming_document函数检查文档语言,必要时执行正确的翻译。

最终结果是一个包含四个主要值的字典:

  • similarity_score:传入文章与数据库中最相似的现有文章之间的得分。

  • is_plagiarism:如果相似度得分等于或超过阈值,则值为true。否则为false。

  • most_similar_article:最相似文章的文本信息。

  • article_submitted:提交审批的文章。

def process_document(text):  
    """  
    Create a vector for given text and adjust it for cosine similarity search  
    """  
    text_vect = create_vector_from_text(tokenizer, model, text)  
    text_vect = np.array(text_vect)  
    text_vect = text_vect.reshape(1, -1)  
  
    return text_vect  
  
  
def is_plagiarism(similarity_score, plagiarism_threshold):  
  
  return similarity_score < plagiarism_threshold  
  
  
def check_incoming_document(incoming_document):  
  
  text_lang = detect(incoming_document)  
  language_list = ['de', 'fr', 'el', 'ja', 'ru']  
  
  final_result = ""  
  
  if(text_lang == 'en'):  
    final_result = incoming_document   
  
  elif(text_lang not in language_list):  
    final_result = None  
  
  else:  
    # Translate in English  
    final_result = translate_text(incoming_document, text_lang)  
  
  return final_result  
  
  
def run_plagiarism_analysis(query_text, data, plagiarism_threshold=0.8):  
  
    top_N=3  
  
    # Check the language of the query/incoming text and translate if required.   
    document_translation = check_incoming_document(query_text)  
  
    if(document_translation is None):  
      print("Only the following languages are supported: English, French, Russian, German, Greek and Japanese")  
      exit(-1)  
  
    else:  
      # Preprocess the document to get the required vector for similarity analysis  
      query_vect = process_document(document_translation)  
  
      # Run similarity Search  
      data["similarity"] = data["vectors"].apply(lambda x: cosine_similarity(query_vect, x))  
      data["similarity"] = data["similarity"].apply(lambda x: x[0][0])  
  
      similar_articles = data.sort_values(by='similarity', ascending=False)[1:top_N+1]  
      formated_result = similar_articles[["abstract", "paper_id", "similarity"]].reset_index(drop = True)  
  
      similarity_score = formated_result.iloc[0]["similarity"]   
      most_similar_article = formated_result.iloc[0]["abstract"]   
      is_plagiarism_bool = is_plagiarism(similarity_score, plagiarism_threshold)  
  
      plagiarism_decision = {'similarity_score': similarity_score,   
                             'is_plagiarism': is_plagiarism_bool,  
                             'most_similar_article': most_similar_article,   
                             'article_submitted': query_text  
                            }  
  
      return plagiarism_decision  

系统实验

我们已经涵盖并实施了工作流程的所有组件。现在,是时候使用我们的系统来测试三种被系统接受的语言:德语、法语、日语、希腊语和俄语。

评估

以下是我们要检查作者是否抄袭的文章摘要文本。

英文文章

这篇文章实际上是源数据中的一个示例。

english_article_to_check = "The need for multidisciplinary research to address today's complex health and environmental challenges has never been greater. The One Health (OH) approach to research ensures that human, animal, and environmental health questions are evaluated in an integrated and holistic manner to provide a more comprehensive understanding of the problem and potential solutions than would be possible with siloed approaches. However, the OH approach is complex, and there is limited guidance available for investigators regarding the practical design and implementation of OH research. In this paper we provide a framework to guide researchers through conceptualizing and planning an OH study. We discuss key steps in designing an OH study, including conceptualization of hypotheses and study aims, identification of collaborators for a multi-disciplinary research team, study design options, data sources and collection methods, and analytical methods. We illustrate these concepts through the presentation of a case study of health impacts associated with land application of biosolids. Finally, we discuss opportunities for applying an OH approach to identify solutions to current global health issues, and the need for cross-disciplinary funding sources to foster an OH approach to research."  

# Select an existing article from the database  
new_incoming_text = source_data.iloc[0]['abstract']  
  
# Run the plagiarism detection  
analysis_result = run_plagiarism_analysis(new_incoming_text, vector_database, plagiarism_threshold=0.8)  

运行系统后,我们得到了一个相似度得分为1,与现有文章完全匹配。这是显而易见的,因为我们从数据库中取了完全相同的文章。

法文文章

这篇文章可以从法国农业网站免费获取。

french_article_to_check = """Les Réseaux d’Innovation et de Transfert Agricole (RITA) ont été créés en 2011 pour mieux connecter la recherche et le développement agricole, intra et inter-DOM, avec un objectif d’accompagnement de la diversification des productions locales. Le CGAAER a été chargé d'analyser ce dispositif et de proposer des pistes d'action pour améliorer la chaine Recherche – Formation – Innovation – Développement – Transfert dans les outre-mer dans un contexte d'agriculture durable, au profit de l'accroissement de l'autonomie alimentaire."""  

analysis_result = run_plagiarism_analysis(french_article_to_check, vector_database, plagiarism_threshold=0.8)  
analysis_result  

在这种情况下,没有发生抄袭,因为相似度得分低于阈值。

德文文章

假设有人非常喜欢数据库中的第五篇文章,并决定将其翻译成德语。现在让我们看看系统如何判断这篇文章。

german_article_to_check = """Derzeit ist eine Reihe strukturell und funktionell unterschiedlicher temperaturempfindlicher Elemente wie RNA-Thermometer bekannt, die eine Vielzahl biologischer Prozesse in Bakterien, einschließlich der Virulenz, steuern. Auf der Grundlage einer Computer- und thermodynamischen Analyse der vollständig sequenzierten Genome von 25 Salmonella enterica-Isolaten wurden ein Algorithmus und Kriterien für die Suche nach potenziellen RNA-Thermometern entwickelt. Er wird es ermöglichen, die Suche nach potentiellen Riboschaltern im Genom anderer gesellschaftlich wichtiger Krankheitserreger durchzuführen. Für S. enterica wurden neben dem bekannten 4U-RNA-Thermometer vier Hairpin-Loop-Strukturen identifiziert, die wahrscheinlich als weitere RNA-Thermometer fungieren. Sie erfüllen die notwendigen und hinreichenden Bedingungen für die Bildung von RNA-Thermometern und sind hochkonservative nichtkanonische Strukturen, da diese hochkonservativen Strukturen im Genom aller 25 Isolate von S. enterica gefunden wurden. Die Hairpins, die eine kreuzförmige Struktur in der supergewickelten pUC8-DNA bilden, wurden mit Hilfe der Rasterkraftmikroskopie sichtbar gemacht."""  

analysis_result = run_plagiarism_analysis(german_article_to_check, vector_database, plagiarism_threshold=0.8)  
analysis_result  

相似度达到了97% - 模型捕捉到了这一点!结果非常令人印象深刻。这篇文章绝对是一个剽窃作品。

结论

恭喜!现在你拥有了构建更强大的抄袭检测系统所需的所有工具,使用BERT和机器翻译模型结合余弦相似度。

如何学习大模型

现在社会上大模型越来越普及了,已经有很多人都想往这里面扎,但是却找不到适合的方法去学习。

作为一名资深码农,初入大模型时也吃了很多亏,踩了无数坑。现在我想把我的经验和知识分享给你们,帮助你们学习AI大模型,能够解决你们学习中的困难。

我已将重要的AI大模型资料包括市面上AI大模型各大白皮书、AGI大模型系统学习路线、AI大模型视频教程、实战学习,等录播视频免费分享出来,需要的小伙伴可以扫取。

一、AGI大模型系统学习路线

很多人学习大模型的时候没有方向,东学一点西学一点,像只无头苍蝇乱撞,我下面分享的这个学习路线希望能够帮助到你们学习AI大模型。

在这里插入图片描述

二、AI大模型视频教程

在这里插入图片描述

三、AI大模型各大学习书籍

在这里插入图片描述

四、AI大模型各大场景实战案例

在这里插入图片描述

五、结束语

学习AI大模型是当前科技发展的趋势,它不仅能够为我们提供更多的机会和挑战,还能够让我们更好地理解和应用人工智能技术。通过学习AI大模型,我们可以深入了解深度学习、神经网络等核心概念,并将其应用于自然语言处理、计算机视觉、语音识别等领域。同时,掌握AI大模型还能够为我们的职业发展增添竞争力,成为未来技术领域的领导者。

再者,学习AI大模型也能为我们自己创造更多的价值,提供更多的岗位以及副业创收,让自己的生活更上一层楼。

因此,学习AI大模型是一项有前景且值得投入的时间和精力的重要选择。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1814329.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

生成高保真度3D数字人化身:打造你的专属虚拟形象

在数字化时代,我们的虚拟形象正变得越来越重要。现在,一项前沿技术正将这一领域推向新的高度——生成高保真度的3D数字人化身。这项技术不仅可以将你的形象以3D形式呈现,更能赋予它生命,让你的虚拟形象拥有丰富的表情和动作。 一、技术简介 这项技术就像是一个高级的3D照…

最简单的方法,连续打印多个空格

1、大家都知道&#xff0c;c语言中&#xff0c;我们打印语句时&#xff0c;如果使用\t来控制打印间隔&#xff0c;可能会出现排版错乱问题&#xff0c;所以一般都会使用空格来控制间隔&#xff0c;这样不管在哪个工具上面显示&#xff0c;打印的信息都不会错乱。 2、控制间隔的…

fdtd(时域有限差分)仿真

FDTD Solutions 是一款非常好用的微纳光学设计工具。该软件提供了丰富的设计功能&#xff0c;支持 CMOS 图像传感器&#xff0c;OLED 和液晶&#xff0c;表面计量&#xff0c;表面等离子体&#xff0c;石墨烯&#xff0c;太阳能电池&#xff0c;集成光子组件&#xff0c;超材 料…

Offline :Adversarially Trained Actor Critic for Offline Reinforcement Learning

ICML 2022 paper code 基于Stackelberg游戏博弈形式&#xff0c;对抗的学习actor与critic Intro Method 将离线RL的Stackelberg博弈表述为一个双层优化问题&#xff0c;学习者策略π∈Π为领导者&#xff0c;批评家f∈F为跟随者: π ^ ∗ ∈ argmax ⁡ π ∈ I I L μ ( π…

JVM如何确定方法调用

方法调用并不等同于方法执行&#xff0c;方法调用阶段唯一的任务就是确定调用哪一个方法&#xff0c;不涉及方法内部的具体运行过程。在程序运行时&#xff0c;进行方法调用是最普遍、最频繁的操作&#xff0c;但Class文件的编译过程中不包含传统编译中的连接步骤&#xff0c;一…

破解动态网页:如何用JavaScript获取自动消失的联想词

前几天在做数据分析时&#xff0c;我尝试获取某网站上输入搜索词后的联想词&#xff0c;输入搜索词后会弹出一个显示联想词的框。有趣的是&#xff0c;当我尝试通过按F12定位这个弹框在HTML中的位置时&#xff0c;输入框失去焦点后&#xff0c;联想词弹框就自动消失了。我观察到…

UnityAPI学习之Animator的基本使用

动画与动画控制器 示例1&#xff1a; 创建Animator对动画控制器进行统一管理&#xff0c;在Gris中创建Animator组件&#xff0c;并对其中的Controller属性进行赋值 在进行动画创作前&#xff0c;需先将图片的Texture Type属性改为Sprite(2D and UI) 再将一系列图片拖入Gris物…

nss刷题(4)

1、[SWPUCTF 2021 新生赛]easyrce <?php error_reporting(0); highlight_file(__FILE__); if(isset($_GET[url])) { eval($_GET[url]); } ?> if(isset($_GET[url])) isset函数用来检测url变量是否存在&#xff1b;$_GET函数获取变量数据 eval($_GET[url]); eval函数用…

基于Java+Swing+mysql幼儿园信息管理系统V2

博主介绍&#xff1a; 大家好&#xff0c;本人精通Java、Python、C#、C、C编程语言&#xff0c;同时也熟练掌握微信小程序、Php和Android等技术&#xff0c;能够为大家提供全方位的技术支持和交流。 我有丰富的成品Java、Python、C#毕设项目经验&#xff0c;能够为学生提供各类…

和鲸101领航北中医:助力健康医疗AI实验室建设,培养交叉数据人才

2024 年 3 月开学季&#xff0c;北京中医药大学&#xff08;简称“北中医”&#xff09;的健康医疗人工智能实验室迎来了正式投入使用后的第一堂课。除了配备全新的桌椅和尖端的硬件服务器外&#xff0c;实验室还引入了先进的人工智能实训平台&#xff0c;为大数据管理与应用专…

Linux1(介绍与基本命令)

目录 一、初始Linux 1. Linux的起源 2. Linux是什么&#xff1f; 3. Linux内核版本 4. Linux的应用 5. 终端 6. Shell 7. Linux目录结构 二、基本命令 1. 基本的命令格式 2. shutdown 关机命令 3. pwd 当前工作目录 4. ls 查看目录内容 5. cd 改变工作目录 …

【制作100个unity游戏之27】使用unity复刻经典游戏《植物大战僵尸》,制作属于自己的植物大战僵尸随机版和杂交版10(附带项目源码)

最终效果 系列导航 文章目录 最终效果系列导航前言使用DoTween优化阳光生成和拾取效果拾取阳光优化生成阳光优化 场景加载进度条新增加载场景Loading&#xff0c;绘制开始界面绘制菜单界面滑动滚轮一直滚动 场景加载源码结束语 前言 本节主要实现使用DoTween优化阳光生成和拾取…

Linux运维实用小脚本,登录即自动显示系统信息

systeminfo.sh #!/bin/bash # systeminfo.sh # by 运维朱工 # site&#xff1a;bash.lutixia.cn ##################################### 获取IP地址和主机名 IP_ADDR$(hostname -I | cut -d -f1) HOSTNAME$(hostname)# CPU负载信息&#xff1a; cpu_load() {echo -e "\…

JAVA基础--MAVEN

MAVEN的认识 什么是MAVEN Maven是一个项目构建及管理工具&#xff0c;开发团队几乎不用花多少时间就能够自动完成工程的基础构建配置&#xff0c; Maven 使用了一个标准的目录结构在不同开发工具中也能实现项目结构的统一。 统一项目结构 Maven提供了清理&#xff0c;编译&a…

【二进制部署k8s-1.29.4】十三、metrics-server的安装部署

文章目录 简介 一.metrics-server的安装 简介 本章节主要讲解metrics-server的安装&#xff0c;metrics-server主要是用于采集k8s中节点和pod的内存和cpu指标&#xff0c;在观察几点和pod的实时资源使用情况还是比较有用的&#xff0c;如果需要记录历史信息&#xff0c;建议采用…

Java到AI大模型,我为什么选择的后者

我为什么从Java转到AI大模型 在编程的海洋里&#xff0c;Java一直是我信赖的“小船”&#xff0c;载着我航行在代码的世界中。然而&#xff0c;随着行业的不断发展和变化&#xff0c;我开始感受到了一丝的迷茫和不安。我开始担心&#xff0c;随着技术的不断更新&#xff0c;Ja…

材料科学基础:期末计算题(第6章)结晶驱动力与过冷度

材料科学基础&#xff1a;计算题&#xff08;第6章&#xff09; 结晶驱动力与过冷度 ∆ G < 0 ; G H − T S ∆G<0; GH-TS ∆G<0;GH−TS d G d T d H d T − S − T d S d T \frac{dG}{dT}\frac{dH}{dT}-S-T\frac{dS}{dT} dTdG​dTdH​−S−TdTdS​ d G d T d H d …

B站画质补完计划(3):智能修复让宝藏视频重焕新生

1 老片存在什么画质问题&#xff1f; B站作为一个拥有浓厚人文属性的平台社区&#xff0c;聚集了诸如《雍正王朝》、《三国演义》等经典影视剧集&#xff0c;同时也吸引了大量用户欣赏、品鉴这些人文经典 。但美中不足的是&#xff0c;由于拍摄年代久远、拍摄设备落后、数据多次…

一次会见苹果App Review专家的在线研讨会

本篇我们来聊聊一次会见苹果App Review专家的见闻&#xff0c;希望能够借助本次会见的内容纪要分享&#xff0c;给广大出海的iOS开发者提供一些有价值的资讯信息&#xff0c;帮助大家都能够轻松应对App的每一次审核。 近期&#xff0c;小编收到了来自苹果设计开发加速器的邀请…

园区无线网新架构:无CAPWAP的集中式转发

1、从经典的APAC组网说起 谈及园区无线网&#xff0c;大家脑子里不免会蹦出同一个关键词。 没错&#xff0c;市面上常见的中大型企业/园区的无线网络组网方案&#xff0c;大多都是基于集中式网关转发的”APAC”模式。 顾名思义&#xff0c;该架构包括 AP 和AC两个关键角色。 …